Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

java - Flatmap vs two forEach

Let's say we have a map of lists and each list contains only one value:

    Map<String, List<String>> map = new HashMap<String, List<String>>();
    
    ArrayList<String> list1 = new ArrayList<String>();
    list1.add("A");
    ArrayList<String> list2 = new ArrayList<String>();
    list2.add("B");
    ArrayList<String> list3 = new ArrayList<String>();
    list3.add("B");
    ...
 // listN.add("N");
    
    map.put("List1", list1);
    map.put("List2", list2);
    map.put("List3", list3);
    ...
//  map.put("ListN", listN);

There is a need to remove duplicates values from all lists via conversion map -> set. So, there are two ways how to do it.

The first one:

Set<String> set = map.values().stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toSet());

The second one:

Set<String> set = new HashSet<>();
map.forEach((k, l)->l.forEach(v->set.add(v)));

The questios are:

  1. What would be better performance?

  2. What would be better performance if each list contains more than one value? As instance:

     Map<String, List<String>> map = new HashMap<String, List<String>>();
    
     ArrayList<String> list1 = new ArrayList<String>();
     list1.add("A");
     list1.add("B");
     list1.add("C"); 
     ArrayList<String> list2 = new ArrayList<String>();
     list2.add("B");
     list2.add("C");
     ArrayList<String> list3 = new ArrayList<String>();
     list3.add("C");
     list3.add("A");
     // and so on
    

From my point of view:

  1. Should be the same performance.
  2. It depends on how flatMap() works under the hood. Can't find any detail source of it. I assume flatMap provide some overhead and should be more slowly.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...