我有List<Person> persons = new ArrayList<>();
我想列出所有唯一的名称。我的意思是,如果有“John”、“Max”、“John”、“Greg”,那么我只想列出“Max”和“Greg”。有没有办法用Java流来做到这一点?
最佳答案
我们可以使用流和Collectors.groupingBy
来计算每个名称出现的次数 - 然后过滤出现多次的名称:
List<String> res = persons.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(e -> e.getKey())
.collect(Collectors.toList());
System.out.println(res); // [Max, Greg]
关于Java流——查找唯一元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283767/