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

Java HashMap adding keys from two different Set sources with stream?

我有一个Set<String> set1Set<String> set2,以及2个函数getSet1ElementScore(String s)getSet2ElementScore(String s)(即return整数)并想插入所有将两个集合中的元素作为其键放入 HashMap 中,每个键的值根据 getSet1ElementScoregetSet2ElementScore 计算得出,具体取决于键来自哪个集合。

我可以使用流来传输吗?

我不是 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);

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

您可以调用适当的函数处理两个集合的元素:

Map<String, String> result = set1.stream()
            .collect(Collectors.toMap(Function.identity(), this::getSet1ElementScore,
                    (old, new) -> old,
                    HashMap::new));
    result.putAll(
            set2.stream()
                    .collect(Collectors.toMap(Function.identity(), this::getSet2ElementScore))
    );

我在第一个处理中显式创建了一个 HashMap,因此它是可变的,我们可以将第二个处理合并到其中。