What is a Java 8 Stream

With Java 8 Streams, we can sort maps by keystroke and value. Here’s how it works:

  1. Convert a collection class object such as a Map or List to a Stream object
  2. The use of Streamssorted()Method to sort them
  3. Finally return it toLinkedHashMap(You can keep the sort order)

The sorted() method takes a Comparator as an argument, allowing the Map to be sorted by any type of value. If you’re not familiar with the Comparator, there was an article a few days ago about sorting lists using the Comparator.

Merge (

Before we get to Map sorting, it’s worth talking about the HashMap merge() function, which is used to deal with elements of a Map when keys are duplicated. This function takes three arguments:

  • Parameter 1: the put key to the map
  • Parameter 2: The value of put to map
  • Parameter 3: What to do with the value if the key is duplicated. It can be a function or it can be written as a lambda expression.
        String k = "key";
        HashMap<String, Integer> map = new HashMap<String, Integer>() {{
            put(k, 1);
        }};
        map.merge(k, 2, (oldVal, newVal) -> oldVal + newVal);
Copy the code

Looking at the code above, we first create a HashMap and put an element with a key of K :1 into it. When we call merge and put k:2 key-value pairs into the map, the k key repeats and the following lambda expression is executed. OldVal + newVal(1+2); now there is only one element in the map and that is k:3.

Lambda expressions are simple: they represent anonymous functions, with arguments to the left of the arrow and function bodies to the right of the arrow. The parameter types and return values of a function are determined by the code context.

3. Sort by Map key

The following example uses a Java 8 Stream to sort by the Map key:

// Create a Map and fill it with data
Map<String, Integer> codes = new HashMap<>();
codes.put("United States".1);
codes.put("Germany".49);
codes.put("France".33);
codes.put("China".86);
codes.put("Pakistan".92);

// Sort by Map key
Map<String, Integer> sortedMap = codes.entrySet().stream()    
        .sorted(Map.Entry.comparingByKey())
        .collect(
                Collectors.toMap(
                    Map.Entry::getKey, 
                    Map.Entry::getValue,
                    (oldVal, newVal) -> oldVal,
                    LinkedHashMap::new));// Print the sorted Map
sortedMap.entrySet().forEach(System.out::println);

Copy the code

Take a look at the second code:

  • The Map type is first converted to the stream type using entrySet().stream().
  • It then uses the sorted method, which is sorted by Map.Entry.comparingByKey(), which is sorted by the Map key
  • Finally, use collect method to transform Stream into LinkedHashMap. Merge (lambda) ¶ Merge (lambda) ¶ Merge (lambda) ¶ Merge (lambda) ¶ merge (lambda) ¶ merge (lambda) Since there are no duplicate keys in this example, you can return either the new or old values.

The above program will print the following on the console, with the keys (country/region names) in natural alphabetical order:

China=86
France=33
Germany=49
Pakistan=92
United States=1
Copy the code

Note the use of LinkedHashMap to store the results of the sort to preserve order. By default, Collectors. ToMap () returns a HashMap. A HashMap does not guarantee the order of elements.

If you want to reverse order by key, add the code shown in red.

4. Sort by Map value

Of course, you can also use the Stream API to sort the Map by its value:

Map<String, Integer> sortedMap2 = codes.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new));

sortedMap2.entrySet().forEach(System.out::println);
Copy the code

This is the output that shows the Map sorted by value:

United States=1
France=33
Germany=49
China=86
Pakistan=92
Copy the code

5. Use TreeMap to sort

You probably know that TreeMap elements are ordered, so TreeMap sorting is a good idea. All you need to do is create a TreeMap object and put the data from HashMapput into TreeMap, very simple:

// Convert 'HashMap' to 'TreeMap'
Map<String, Integer> sorted = new TreeMap<>(codes);
Copy the code

Here is the output:

China=86
France=33
Germany=49
Pakistan=92
United States=1
Copy the code

As shown above, the keys (country/region names) are sorted in natural alphabetical order.

We look forward to your attention

  • The blogger has recently written a new book: “SpringBoot Series – Chapter 16, Verse 97.”
  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.