Java 8 – How to Sort HashMap entries? (Remove Null, Sort By Keys and Collect Values Only)

Java8 Stream Hashmap Sort –> You might find it a little off the line but recently took a small session with my team on how best they can use Java 8 to improve their coding practices and delivery. Took below example to explain them the simplicity it brings to coding and hence sharing as a small post. Hope it is still helpful for many ๐Ÿ™‚

Java8 Stream Hashmap Sort

Problem Statment :

Java8 Stream Hashmap Sort – We have a Hash Map with key-value pairs where one of the key is Null. Requirement is to

  • a) remove null values
  • b) sort the entries by key
  • c) collect the values as an ordered list

Solution using Java8 Stream Hashmap Sort:

Check this example prgoram

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MapSortByKeyAndCollectValues {
    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(45, "A");
        map.put(23, "C");
        map.put(1, "B");
        map.put(null, "remove Me");

        List newList = map.entrySet().stream().filter(x -> x.getKey()!=null).sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).collect(Collectors.toList());
  
          System.out.println(newList);

    }
}
  • // map.entrySet().stream() –> Get Map Entries and stream
  • // .filter(x -> x.getKey()!=null) . –> Removes Entries with Null Key
  • // .sorted(Map.Entry.comparingByKey()) –> Sort Entris by Key
  • // .map(Map.Entry::getValue) –> Only gets the Value object from Entry
  • // .collect(Collectors.toList()) . –> Collects the Values in List Object

STREAM? ย Aย streamย is a sequence of objects that supports various methods which can be pipelined to produce the desired result.

A wonderful article and samples are available at Oracle website @ https://www.oracle.com/technical-resources/articles/java/architect-streams-pt2.html

Related Posts

2760cookie-checkJava 8 – How to Sort HashMap entries? (Remove Null, Sort By Keys and Collect Values Only)

Leave a Reply

Your email address will not be published.