[英]How to limit in groupBy java stream
This is my course model in class named Course
: 这是我课程中名为
Course
课程模型:
public class Course{
private int courseId;
private String courseName;
private Teacher teacher;
}
This is my teacher model in class named Teacher
: 这是我在班级
Teacher
老师模型:
public class Teacher{
private int teacherId;
private String name;
}
I want to get a Map<String, List<Course>>
but if the teacherId
is repeated just add that Course
into list of map. 我想获得一个
Map<String, List<Course>>
但是如果要重复teacherId
,只需将该Course
添加到地图列表中。
I am using groupBy
for it 我正在使用
groupBy
Map<Integer, List<Course>> result = courses.stream()
.collect(Collectors.groupingBy(c -> c.getTeacher().getTeacherId(), Collectors.toList()));
and it's giving result as expected. 它正在按预期给出结果。
But I want to limit
here that As soon as 5 teachers are found stop to process and returned the result. 但我想在此
limit
,只要找到5名教师停止处理并返回结果。
How can it be done?? 如何做呢??
There's no direct support for this, as stopping and living with potentially incomplete data is rather unusual. 没有直接支持这一点,因为停止和生活可能不完整的数据是相当不寻常的。
A straight-forward solution collecting the first five groups completely, would be 完全收集前五个组的直接解决方案是
Set<Integer> firstFive = courses.stream()
.map(c -> c.getTeacher().getTeacherId())
.distinct().limit(5)
.collect(Collectors.toSet());
Map<Integer, List<Course>> result = courses.stream()
.filter(c -> firstFive.contains(c.getTeacher().getTeacherId()))
.collect(Collectors.groupingBy(c -> c.getTeacher().getTeacherId()));
Here, the Course
lists of these first five teacher ids are complete. 这里,前五个教师ID的
Course
列表已经完成。
A solution that truly stops after encountering the 5th teacher id, would be simpler with a loop: 在遇到第5个教师ID后真正停止的解决方案,循环更简单:
Map<Integer, List<Course>> result = new HashMap<>();
for(Course c: courses) {
result.computeIfAbsent(c.getTeacher().getTeacherId(), x -> new ArrayList<>()).add(c);
if(result.size() == 5) break;
}
But there is not much sense in collecting lists of Course
s, when you can't trust these lists afterwards. 但收集
Course
列表没有多大意义,之后你不能相信这些列表。 Keep in mind, that even the source list's very last element could belong to the first encountered teacher ID, so you need to process the entire list even if you are interested in only one teacher's complete list of courses. 请记住,即使源列表的最后一个元素也可能属于第一个遇到的教师ID,因此即使您只对一个教师的完整课程列表感兴趣,也需要处理整个列表。
Not sure if this is what you are asking. 不确定这是不是你要问的。
Map<Integer, List<Course>> map = new HashMap<>();
courses.stream().filter(course -> map.keySet().size() < 10)
.forEach(entry -> {
// The code below can be simplified
int teacherId = entry.getTeacher().getTeacherId();
if(map.get(teacherId) != null)
map.get(teacherId).add(entry);
else
map.put(teacherId, Lists.newArrayList(entry));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.