我知道下面是找出列表中每个 String 属性出现的代码,我怎样才能过滤这个列表只有重复的项目,即出现超过 1 次。对不起,我是 java 8 的新手。
Map<String, Long> result = list.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
最佳答案
从 entrySet
和 filter
创建一个流:
List<Map.Entry<String, Long>> result = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(s -> s.getValue() >= 2)
.collect(Collectors.toList());
或者如果你想维护一个 map ,那么:
Map<String, Long> result = stringList().stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(s -> s.getValue() >= 2)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
另一方面,如果您只想要出现次数大于或等于 2 次的单个数字,那么您可以这样做:
List<String> result = list.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.entrySet()
.stream()
.filter(x -> x.getValue() >= 2)
.map(Map.Entry::getKey)
.collect(toList());
另一种选择是:
List<String> result =
list.stream()
.filter(x -> list.stream().filter(x::equals).limit(2).count() == 2)
.distinct()
.collect(toList());
关于java - 使用 Java 8 在列表中仅查找重复的字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53584012/