将列表转换为从列表中的唯一值的地图,用键作为单个元素
continue
I have a list as below -
List<List<String>> originalList =
List.of(List.of("C1", "C2", "C3"), List.of("C2", "C3", "C1"));
I am collecting unique elements across lists and arrived at -
Set<String> uniqueValues = originalList.stream()
.flatMap(Collection::stream)
.collect(Collectors.toSet());
Now I'm trying to create a map which will look like below -
{C3=[C1, C2], C1=[C3, C2], C2=[C3, C1]}
I have the below snippet -
Map<String, Set<String>> mymap = uniqueValues
.stream()
.collect(Collectors.toMap(Function.identity(),
value -> uniqueValues, (left, right) -> {
left.removeAll(right);
return left;
}));
which is giving me -
{C3=[C3, C1, C2], C1=[C3, C1, C2], C2=[C3, C1, C2]}
What am I doing wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上,您的目标是创建一个地图,每个条目代表基于Set
uniqueValues
生成的组合。显然,每种组合都是不同的,这意味着它需要自己的
set
。 IE而不是为每个 key 提供unique>
uniquevalues
并从中删除当前键。另一个错误是,您不需要
tomap()
收集器的味道,它期望三个参数,因为MergeFunction
(第三个参数)旨在解决重复项,但会在其中解决。由于其源为set
,因此在流中没有重复。为此,我们需要一个版本的
tomap
只期望keymapper
(( 一个从流元素)和valueMapper
( 函数负责从流元素生成值的函数)的函数。That's how it can be done:
Output:
Basically, your goal is to create a map where each entry represents a combination generated based on a set
uniqueValues
.And obviously each combination is distinct, which means it requires its own
Set
. I.e. instead of providing theuniqueValues
as a value for every key, you need to generate a newHashSet
based on theuniqueValues
and remove the current key from it.Another mistake is that you don't need a flavor of
toMap()
collector that expects three arguments becausemergeFunction
(the third argument) is meant to resolve duplicates, but there would be no duplicates in the stream since its source is aSet
.To achieve this we need a version of
toMap
that expects only akeyMapper
(a function which produces a key from a stream element) andvalueMapper
(a function responsible for generating a value from a stream element).That's how it can be done:
Output: