There are two ways to sort a property of an object in a collection.
A. One is to sort the object class to implement the comparable interface CompareTo method, then put the object into the list, then call Collections.sort (list);B. One is not to make any changes to the Sort object class, create the implementation class C of the comparator interface, then put the object into the list, and then call Collections.sort (list, C);
A.eg
---------------------
1, the entity class implements the comparable interface, the rewriting CompareTo method
Package io;
Import Java.text.DateFormat;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
public class Student implements comparable
Package io;
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.List;
public class App. {public
static void Main (string[] args) {
list
2, create a new business class implementation
Because the original sort API is actually the first to compare the number of converted to a string and then compare, so it is not easy to useSo prepare to customize a comparer function:1 //Sort Principle--->sort (arr,compare)2 functionSort (arr,compare) {3 if(compare===undefined) {//If compare is undefined, a compare original comparator is created, converted to a string for comparison, and if a custom comparer is passed in, the custom co
Goal: Achieve the age of the person object, from small to large sort1. Implementation sequencing1 PackageCom.app;23 Importjava.util.ArrayList;4 Importjava.util.Collections;5 ImportJava.util.Comparator;6 Importjava.util.List;7 8 Public classA1extendsb{9 Ten Public Static voidMain (string[] args) { OnelistGetData (); A //Sort - Collections.sort (list, comparator); - the for(person person:list) { -System.out.println ("per
Http://www.verejava.com/?id=169931036202101/** Knowledge Points: Comparative class Comparator title: A class of students according to mathematical results from small to large order of thought: 1. Abstract class: 1.1 Class (Classset) 1.2 Students (St Udent) 2. Find out the class relationship: 2.1 Students belong to class Student-Classset (many to 1) 3. Find class Properties: 3.1 Classset (class name, class number) 3.2 Student (student name, math score)
packagecom.heli.compare;importjava.text.collator;importjava.util.comparator;import java.util.locale;/*** @desc person class. person implements the comparable interface, which means that the person itself supports sorting */publicclassPersonimplements comparable packagecom.heli.compare;importjava.util.arraylist;importjava.util.collections;public Classtest{publicstaticvoidmain (String[]args) {// new ArrayList ( Dynamic array) arraylist Comparator sorted
sorting function has already been implemented in Java APIs. We do not haveWe need to repeat the wheel.
The arrays class has a static method sort. With this method, we can import the array we want to sort into the sorting. Because we pass in an array reference, the sorting is complete.The result also uses this reference to change the array. for sorting integers and strings, JDK provides the default implementation. If you want to sort an array of objects, you must implementJava. util.
Business requirements:Descending by number of participants, then by rank and ascendingNumber of people: pertotal, ranking of the sum: ranktotalFull code:@Overridepublic jsonobject gettopunitofgameranking (listkey part code (in the same number of cases, compare the sum of the rankings):listExamples of comparator in Java
Define binary operation class Binarytree{class node{private node left;//index private node right;//index private comparable data;public node (comparable This method is generally not recommended, direct recommendation, implements comparable, implement Comparato () methodJava:comparable Comparator, define binary operation class
Review. Record it by the way!
Use collections. SortAndArrays.sortThere are two methods for sorting objects. The comparable interface of sorting objects overrides the compareto method and transmits the parameters for implementing the comparator interface to the sort method. The following sortobject object, the two methods are implemented.
Package Oliver. java. Test. Sort;
Test code:
Package Oliver. java. test. sort;
public class CompareToImplementsComparator implements Comparator { public int compare(Object o1, Object o2) { int i=(Integer)o1; int j=(Integer)o2; if(i>j){ return 1; } return 0; } @SuppressWarnings("unchecked") public static void main(String[] args) { List for(int i=10;i>0;i--){ list.add(i); } Collections.sort(list, new CompareToImplementsComparator()); for(int j=0;j System.out.prin
PackageCom.swift;Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List; Public classMax_substring_test { Public Static voidMain (string[] args) {/** Maximum common substring of several strings*/String str1= "Eriousdfndnfdlk"; String str2= "Dkgfdkgkdjgdjgjksjgksgjsdkjsdierioe"; String STR3= "Ldskfjdskierundsnfjerioejrejrheruer3j43j4hj3"; String Sub; ListNewArraylist(); for(inti = 0; I ) {Sub= str1.substring (0, i); if(Str2.indexof (s
In practice, we often have to implement some of the more bizarre sort.
For example, in a group of [1,3,5,8,4,6,5], keep the original order unchanged, in the order of size. and establish a mapping relationship. (after sorting, use O (1) complexity to query the position of the first large number in the original array)such as thisIndex 0 1 2 3 4 5 6Arr 1 3 5 8 4 6 5Sort 6 5 2 0 4 1 3
For the algorithm party, this time can hand tear a fast platoon or merge and so on. (But if it's in the game,
TreeMap, Comparable, and Comparator in JavaWe know that the storage location of HashMap is stored according to the hashCode of the key object, while that of TreeMap is stored according to the hashCode, it is stored according to the compareTo method of the implemented Comparable interface. As long as the returned result of compareTo is 0, the two objects are equal, so there will be no two objects, the put method overwrites the previous one. We don't ev
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.