javadictionaryhashmapjava-stream

Adding keys to a HashMap from two different Set sources, using two different functions, using a stream


I have a Set<String> set1 and Set<String> set2, as well as 2 functions getSet1ElementScore(String s) and getSet2ElementScore(String s) (that return Integers) and want to insert all elements from both sets into a HashMap as its keys, with each key's value either calculated from getSet1ElementScore or getSet2ElementScore depending on which set the key came from.

Can I use a stream to pipeline this?


Solution

  • I'm not 100% sure I got your question right. This might achieve what you want:

    Set<String> set1 = new HashSet<>();
    Set<String> set2 = new HashSet<>();        
            
    Map<String, String> mapFromSet1 =
      set1.stream().collect( Collectors.toMap(Function.identity(), p -> getSet1ElementScore(p)) );
    Map<String, String> mapFromSet2 =
      set2.stream().collect( Collectors.toMap(Function.identity(), p -> getSet2ElementScore(p)) );
            
    Map<String, String> resultMap =  new HashMap<>();
    resultMap.putAll(mapFromSet1);
    resultMap.putAll(mapFromSet2);
    

    In order to transform it in one single pipeline, I think it is possible but you'd need to use (unnecessarily) more code than that.