## 0 foreword

Sorting Lists (mainly ArrayList) and Maps (mainly HashMap) is the most common business scenario, so it’s worth systematically reviewing and learning about them. This article summarizes the commonly used sorting methods.

## 1 a List sorted

### 1.1 Sorting of basic data types

A. Numerical data

``// import org.junit.test; import org.junit.test; import org.junit.test; import java.text.Collator; import java.util.*; import java.util.stream.Collectors; @Test public void intTest() { List<Integer> intList = new ArrayList<>(); intList.add(1); intList.add(5); intList.add(4); Println (" original: "+ intList); / / inverted Collections. Reverse (intList); System.out.println(" Inverted: "+ intList); / / sorting intList. Sort (Comparator. NaturalOrder ()); System.out.println(" positive: "+ intList); intList.sort(Comparator.reverseOrder()); Println (" in reverse order: "+ intList); }``

Output results:

``Original: [1, 5, 4) inversion: [4, 5, 1] positive sequence: [1, 4, 5] : in reverse chronological order (5, 4, 1)``

B. Character data

The sorting of English characters is in alphabetical order, and the specific operation is similar to numerical sorting. Here, I would like to give a special introduction to the sorting of Chinese characters. The common way is to arrange the first characters in alphabetical order.

``@Test public void strTest() { List<String> strList = new ArrayList<>(); StrList. Add (" wuhan "); StrList. Add (" Beijing "); StrList. Add (" Shanghai "); System.out.println(" original: "+ strList); Collator.getInstance(locale.china); // Collator instance = collator.getInstance (locale.china); Strlist.sort (instance); strlist.sort (instance); strlist.sort (instance); strlist.sort (instance); strlist.sort (instance); System.out.println(" positive: "+ strList); strList.sort(instance.reversed()); System.out.println(" reverse: "+ strList); }``

Output results:

``Original: [Wuhan, Beijing, Shanghai] Forward: [Beijing, Shanghai, Wuhan] Inverse: [Wuhan, Shanghai, Beijing]``

### 1.2 Sorting of JavaBeans type

Customize a JavaBean:

``public class A implements Comparable<A> { private String name; private Integer order; public A(String name, Integer order) { this.name = name; this.order = order; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } @Override public String toString() { return "order=" + order+ " name=" + name; } @Override public int compareTo(A a) { return this.order.compareTo(a.getOrder()); }}``

For custom JavaBean types, there are several common sorting methods:

``@Test public void objectTest() { List<A> listA = new ArrayList<>(); listA.add(new A("a2", 1)); listA.add(new A("a3", 3)); listA.add(new A("a3", 2)); listA.add(new A("a1", 3)); Println (" original: "+ listA); // Comparable is an object in the list that implements the Comparable interface and directly sort lista. sort(comparator.naturalOrder ()); System.out.println("1. Based on order -- method 1: "+ listA); Comparator.com Paring (A::getOrder). Comparator.com Paring (A::getOrder). Comparator.com Paring (A::getOrder). Comparator.com Paring (A::getOrder). Comparator.com Paring (A::getOrder). System.out.println("1. Based on order -- method 2: "+ listA); // from List<A> result1 = listA.stream().sorted(Comparator.comparing(A::getOrder).thenComparing(A::getName)).collect(Collectors.toList()); System.out.println("2. Sort order and name in ascending order based on A -- method 2 extension: "+ result1); // from List<A> result2 = listA.stream().sorted(Comparator.comparing(A::getOrder).thenComparing(A::getName).reversed()).collect(Collectors.toList( )); System.out.println("3. Descending order and name based on A -- method 2 extension: "+ result2); // 1. CompareTo (a2. CompareTo (a2. CompareTo (a2. CompareTo (a2. listA.sort(Comparator.comparing(A::getOrder).thenComparing(comparatorName)); System.out.println("4. Sort order based on A and name in descending order -- "+ listA); // Method 3: > Comparator = (1, 1, 1, 2) a2) -> { if (a1.getOrder().equals(a2.getOrder())) { return -a1.getName().compareTo(a2.getName()); } return a1.getOrder().compareTo(a2.getOrder()); }; listA.sort(comparator); System.out.println("4. Based on order and name descending -- "+ listA); }``

Running results:

``[order=1 name=a2, order=3 name=a3, order=2 name=a3, order=3 name=a1] 1. [order=1 name=a2, order=2 name=a3, order=3 name=a3, order=3 name=a1] 1 [order=1 name=a2, order=2 name=a3, order=3 name=a3, order=3 name=a1] 2 [order=1 name=a2, order=2 name=a3, order=3 name=a1, order=3 name=a3] 3 [order=3 name=a3, order=3 name=a1, order=2 name=a3, order=1 name=a2] 4 [order=1 name=a2, order=2 name=a3, order=3 name=a3, order=3 name=a1] 4 [order=1 name=a2, order=2 name=a3, order=3 name=a3, order=3 name=a1]``

## 2 the Map sort

### 2.1 Sorting of basic data types

The commonly used map structure for storing data is HashMap, which has high efficiency of adding, deleting, modifying and searching. However, HashMap cannot record the order of data, so LinkedHashMap is often used for sorting to store ordered data.

1.
https://blog.csdn.net/qq_2876…

2,
https://www.cnblogs.com/coder…

``@Test public void test(){ Map<String, Double> map = new HashMap<>(); The map. The put (" b ", 0.08); The map. The put (" a ", 0.1); The map. The put (" c ", 0.02); The map. The put (" d ", 0.91); System.out.println(" original: "+map); Map<String, Double> result = new LinkedHashMap<>(); map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); Println (" in ascending order by key: "+result); Map<String, Double> result2 = new LinkedHashMap<>(); map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(e -> result2.put(e.getKey(), e.getValue())); System.out.println(" in ascending order by value: "+result2); }``

Running results:

``Original: {= 0.1 a, b = 0.08, c = 0.02, d = 0.91} according to the key ascending order: {= 0.1 a, b = 0.08, c = 0.02, d = 0.91} according to the value ascending order: {c = 0.02 a, b = 0.08, a = 0.1, 0.91} d =``

You can add reversed after ComparingByKey or ComparingByValue, encapsulating the sort method as follows:

``@return */ public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isReverse) { Map<K, V> result = new LinkedHashMap<>(); if (isReverse) { map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); } else { map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); } return result; } /* * @Param isReverse = @Param isReverse = @Param isReverse = @Param isReverse = @Return */ public <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isReverse) { Map<K, V> result = new LinkedHashMap<>(); if (isReverse) { map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); } else { map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); } return result; }``

In addition to HashMap and LinkedHashMap, there is another structure that does not require additional sorting operations and is stored in an ordered manner, called a TreeMap.

A detailed introduction to TreeMap:

1.
https://blog.csdn.net/chenssy…

2,
https://www.liaoxuefeng.com/w…

Its use method is as follows:

``@Test public void treeMapTest(){ TreeMap<String,Double> map = new TreeMap<>(); The map. The put (" b ", 0.08); The map. The put (" a ", 0.1); The map. The put (" c ", 0.02); System.out.println(" Default in key positive order :"+map); TreeMap<String,Double> map2 = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return -o1.compareTo(o2); }}); Map2. Put (" b ", 0.08); Map2. Put (" a ", 0.1); Map2. Put (" c ", 0.02); System.out.println(" key = "+map2); }``

Note: TreeMap only supports sorting on key. If you want to sort on value, you need to convert it to list and then sort.

### 2.2 Sorting of JavaBeans type

A common scenario is when the value of a map stores a JavaBean that needs to be sorted by the fields in the JavaBean. For example, sort by A in ascending order and name in descending order.

``@Test public void objectTest(){ Map<String, A> map = new HashMap<>(); map.put("b", new A("a2", 1)); map.put("a", new A("a3", 3)); map.put("c", new A("a3", 2)); map.put("d", new A("a1", 3)); Map<String, A> result = new LinkedHashMap<>(); Comparator<Map.Entry<String, A>> comparator = (c1, c2) -> { A a1=c1.getValue(); A a2=c2.getValue(); if (a1.getOrder().equals(a2.getOrder())) { return -a1.getName().compareTo(a2.getName()); } return a1.getOrder().compareTo(a2.getOrder()); }; map.entrySet().stream().sorted(comparator).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); Println (" in ascending order of value: "+result); }``

Running results:

``{b=order=1 name=a2, c=order=2 name=a3, a=order=3 name=a3, d=order=3 name=a1}``