英文:
Java HashMap adding keys from two different Set sources with stream?
问题
我有一个 Set<String> set1
和 Set<String> set2
,以及两个函数 getSet1ElementScore(String s)
和 getSet2ElementScore(String s)
(返回整数),我想将两个集合中的所有元素都插入到一个 HashMap 中作为其键,每个键的值要么是从 getSet1ElementScore
计算得出的,要么是从 getSet2ElementScore
计算得出的,具体取决于该键是来自哪个集合。
我能使用流来进行处理吗?
英文:
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?
答案1
得分: 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);
为了将其转换为单个流水线,我认为可能性是存在的,但你可能需要使用(不必要的)比这更多的代码。
英文:
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.
答案2
得分: 2
你可以调用适当的函数处理这两个集合的元素,如下所示:
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,这样它就是可变的,我们可以将第二个处理合并到其中。
英文:
You can process the elements of the two sets calling the appropriate function as:
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))
);
I explicitly created a HashMap in the first processing so that it is mutable and we can merge the second into it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论