Java HashMap 使用流从两个不同的 Set 源添加键?

Ste*_* Fu 1 java hashmap stream

我有一个Set<String> set1and Set<String> set2,以及 2 个函数getSet1ElementScore(String s)and getSet2ElementScore(String s)(返回整数),并且想要将两个集合中的所有元素作为其键插入到 HashMap 中,每个键的值要么根据键来自哪个集合计算,getSet1ElementScore要么getSet2ElementScore取决于键来自哪个集合。

我可以使用流来进行管道传输吗?

小智 5

我不是 100% 确定我问对了你的问题。这可能会实现您想要的:

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);
Run Code Online (Sandbox Code Playgroud)

为了在单个管道中转换它,我认为这是可能的,但是您需要(不必要地)使用比这更多的代码。