gpt4 book ai didi

java - 编译错误 : cannot convert Set> to Set>>

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:57 30 4
gpt4 key购买 nike

我是流的新手,我想通过将流操作应用于其条目集来修改 map ,但由于编译错误我无法这样做。

下面的代码只是创建了一个新的 map 对象并为其分配了一些整数值。然后它尝试通过在其条目集上应用流操作来删除映射并将其分配给另一个集合来修改映射。

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

class Example {
public static void main (String[] args) {
Map<Integer, Set<Integer>> map = new HashMap<>();

map.put(1, new HashSet<>());
map.put(2, new HashSet<>());
map.put(3, new HashSet<>());

for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
map.get(i).add(j);

Set<Map.Entry<Integer, Set<Integer>>> set = map.entrySet().stream()
.filter(e -> !e.equals(1))
.map(e -> e.setValue(e.getValue().stream()
.filter(x -> !x.equals(1))
.collect(Collectors.toSet())))
.collect(Collectors.toSet());
System.out.println(set);
}
}

上面的代码给出了编译错误,我不知道为什么,因为我看它的方式,它看起来很好。要在上面的代码中进行哪些更改才能成功编译?

最佳答案

1) 过滤 Map 中哪些键不等于 1 的条目(因为 Map 不允许重复的键,您将只有一个键为 1 的条目)

2) 过滤器 Set(因为 Set 不允许重复,所以只有一个值 1)

Set<Map.Entry<Integer,Set<Integer>>> result =  map.entrySet()
.stream()
.filter(e->!e.getKey().equals(1))
.map(entry->new AbstractMap.SimpleEntry<Integer, Set<Integer>>(entry.getKey(),entry.getValue().stream().filter(i->!i.equals(1)).collect(Collectors.toSet())))
.collect(Collectors.toSet());

关于java - 编译错误 : cannot convert Set<Set<T>> to Set<Map. Entry<T, Set<T>>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465592/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com