在TreeMap上应用Distinct函数 [英] Apply Distinct Function on TreeMap
问题描述
代码:
Map<Integer, HashSet<String>> test = new TreeMap<>();
test.put(1, new HashSet<>());
test.put(2, new HashSet<>());
test.put(3, new HashSet<>());
test.put(4, new HashSet<>());
test.get(1).add("1");
test.get(2).add("2");
test.get(3).add("2");
test.get(4).add("3, 33");
//get value of treemap and get rid of the duplicate by using distinct and printout
//at the end
test.values().stream().distinct().forEach(i -> System.out.println(i));
输出:
[1]
[2]
[3, 33]
我的问题是如何在没有重复值的情况下同时打印出键和值?
预期结果:
1= [1]
2= [2]
3= [3, 33]
我甚至尝试下面的代码,但它给了我带有重复值的树形图:
代码:
List<Map.Entry<Integer, HashSet<String>>> list = new ArrayList<>();
list.addAll(test.entrySet());
list.stream().distinct().forEach( i -> System.out.println(i));
输出:
1=[1]
2=[2]
3=[2]
4=[3, 33]
推荐答案
test.entrySet().stream()
.collect(
Collectors.toMap(
Map.Entry::getValue,
x -> x,
(a, b) -> a
)
).values()
.forEach(System.out::println);
修改:
说明:此代码段将获取条目流并将它们放入要输入的值的映射中,同时丢弃重复项(请参阅javadoc以获取收藏家#toMap )。然后,它将该映射的值作为集合。结果是收集了由 Map.Entry :: getValue
分隔的映射条目。
Explanation: this snippet will take the stream of entries and put them into a map of value to entry while discarding duplicates (see javadoc for Collectors#toMap). It then takes the values of that map as a collection. The result is the collection of map entries that are distinct by Map.Entry::getValue
.
编辑2:
从您的评论我想我明白你是什么试图做。您正在使用此TreeSet作为基于1的列表,并且您希望在删除重复值时折叠键。那是对的吗?也许你可以解释为什么你这样做而不只是使用列表。
From your comments I think I understand what you are trying to do. You are using this TreeSet as a 1-based list and you want keys to collapse as you remove duplicate values. Is that correct? Maybe you can explain why you are doing this instead of just using a list.
Streams不适合这种方法,所以这不会很漂亮,但在这里你去:流式传输数值,消除重复数据,收集到列表中,然后将列表转回地图。
Streams aren't well-suited for this sort of approach, so this will not be pretty, but here you go: Stream the values, eliminate duplicates, collect into a list, then turn the list back into a map.
test.values().stream()
.distinct()
.collect(
Collectors.collectingAndThen(
Collectors.toList(),
lst -> IntStream.range(0, lst.size()).boxed().collect(
Collectors.toMap(i -> i + 1, i -> lst.get(i))
)
)
).entrySet().forEach(System.out::println);
output:
1=[1]
2=[2]
3=[3, 33]
这篇关于在TreeMap上应用Distinct函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!