Collection API Enhancement in Java8

Reading Time: 2 minutes

In this blog, we will discuss the java collection enhancements which we have got in java 8.

Let’s see the enhancements with the examples –

comparingByKey and comparingByValue

If we want to sort the Map in the functional and elegant way in java 8 or 8+. We can achieve it by using comparingByKey() and comparingByValue() methods introduced in java 8.

The name is self-explaintary comparingByKey() is used for sort by key and comparingByValue() is used for sort by value in the hashmap.

public class MapComparator {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("C", "c");
        map.put("B", "b");
        map.put("Z", "z");
        List<Map.Entry<String, String>> sortedByKey = map.entrySet()
                .stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toList());
    }
}

This is an example of how we used to sort the map before the java 8 enhancement.

 // first converting map to list.
        List<Map.Entry<String, String>> studentList =
                new LinkedList<Map.Entry<String, String>>(studentMap.entrySet());

        // Sort the list.
        Collections.sort(studentList, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> entry1,
                               Map.Entry<String, String> entry2) {
                return (entry1.getValue()).compareTo(entry2.getValue());
            }
        });

        // put data from sorted list to hashMap.
        HashMap<String, String> sortedHashMap = new LinkedHashMap<String, String>();
        for (Map.Entry<String, String> aa : studentList) {
            sortedHashMap.put(aa.getKey(), aa.getValue());
        }

getOrdefault

getOrdefault method returns the mapped value to corresponding key from the map and if there is no key present then it will return the default value.


        Map<String, String> studentMap = new HashMap<>();
        studentMap.put("key1", "12345");
        String val1 = studentMap.getOrDefault("key1", "0");
        String val2 = studentMap.getOrDefault("key2", "0");

        System.out.println(val1);  // 12345
        System.out.println(val2);  // 0
        System.out.println(studentMap.get("key2")) // null

compute

If we want to modify a value which is mapped to key in the map then what will be steps to get it done –

  • First fetch the value by the help of the corresponding key.
  • Modify the value
  • Then put the modified value to the same key.
HashMap<String, String> studentMap = new HashMap<>();
        studentMap.put("C", "c");
        studentMap.put("B", "a");
        studentMap.put("Z", "b");
        
        studentMap.put("B",studentMap.get("B")+"1");
        System.out.println(studentMap.get("B")); // a1

But now, we have a more elegant way to do it by using compute method.

HashMap<String, String> studentMap = new HashMap<>();
        studentMap.put("C", "c");
        studentMap.put("B", "a");
        studentMap.put("Z", "b");

        studentMap.compute("B", (k, v) -> v.concat("2"));
        System.out.println(studentMap.get("B"));  // a2

putIfAbsent

We don’t need to check that a key is mapped in the map or not. We can directly use the putIfAbsent method to put the key into the map, if the key already exists in the map then corresponding value will not modify but if key doesn’t exist in the map then put operation will be performed.

HashMap<String, String> studentMap = new HashMap<>();
        studentMap.put("C", "c");
        studentMap.put("B", "a");
        studentMap.put("Z", "b");
        studentMap.putIfAbsent("Z","1");
        studentMap.putIfAbsent("A","2");
        System.out.println(studentMap.get("A")); // 2
        System.out.println(studentMap.get("Z")); // b

That’s all for the java-8 enhancement in collections, if you have any more queries or want to know more about it you can add the comment. I am happy to answer them. 


Knoldus-blog-footer-image

Written by 

Lokesh Aggarwal is a software Consultant trainee with 6 months of experience at Knoldus Inc.

1 thought on “Collection API Enhancement in Java83 min read

  1. Awesome article put in simple way with small good examples. Liked it very much

Comments are closed.

%d bloggers like this: