按编号分组,查找大小超过1的组 2.检查组是否包含条件(字符串!= null)
2a. if yes ---> remove all rows which do not have a condition (string == null)
2b. if no ---> return the group as it is (no filtering at all)
我正在尝试下面的代码,但我无法在此处过滤条件。有没有简单的方法呢?
groupByList = list.stream().collect(Collectors.groupingBy(student::no));
groupByList.values().stream().map(group -> group.size() > 1)
.collect(Collectors.toList());
答案 0 :(得分:0)
您需要同时使用Stream.filter(..)和Stream.map(..)
// Groups students by group number
Map<String, List<Student>> allGroups = list.stream().collect(Collectors.groupingBy(student::no));
// Filters groups that have more than 1 member
Map<String, List<Student>> filteredGroups = allGroups.entrySet().stream().filter(entry -> entry.getValue().size() > 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Removes all non-null members
Map<String, List<Student>> cleanGroups = filteredGroups.entrySet().stream()
.map(entry -> {
entry.setValue(entry.getValue().stream().filter(student -> student.name != null).collect(Collectors.toList()));
return entry;
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
您可以将执行管道化为一个大链:
Map<String, List<Student>> cleanGroups = list.stream()
.collect(Collectors.groupingBy(student::no))
.entrySet().stream()
.filter(entry -> entry.getValue().size() > 1)
.map(entry -> {
entry.setValue(entry.getValue().stream()
.filter(student -> student.name != null)
.collect(Collectors.toList()));
return entry;
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
请注意,您有一个隐藏的对象转换,上面有.filter(..)。collect(..)。如果你需要跳过它(以双重比较为代价),你可以将lambda方法扩展为:
.map(entry -> {
if (entry.getValue().stream.anyMatch(student.name == null)) {
entry.setValue(entry.getValue().stream().filter(student -> student.name != null).collect(Collectors.toList()));
}
return entry;
})