top of page

New computeifabsent method in Map

  • taolius
  • Feb 12, 2018
  • 1 min read

https://stackoverflow.com/questions/19278443/how-do-i-use-the-new-computeifabsent-function

This is really helpful if you want to create a Multimap without using guava library (https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html)

For eg: If you want to store a list of students who enrolled for a particular subject. The normal solution for this using jdk library is

Map<String,List<String>> studentListSubjectWise = new TreeMap<>();

List<String>lis = studentListSubjectWise.get("a");

if(lis == null) {

lis = new ArrayList<>();

}

lis.add("John"); //continue....

Since it have some boiler plate code, people tend to use guava Mutltimap.

Using Map.computeIfAbsent, we can write in a single line without guava Multimap as follows.

studentListSubjectWise.computeIfAbsent("a", (x -> new ArrayList<>())).add("John");

Stuart Marks & Brian Goetz did a good talk about this https://www.youtube.com/watch?v=9uTVXxJjuco


 
 
 

Comments


© 2023 by BI World. Proudly created with Wix.com

  • Facebook Basic Black
  • Twitter Basic Black
  • YouTube Basic Black
bottom of page