我有“学生”类的数组。学生班有两个字段:1.private final String firstName; 2. private最终布尔值isCurrent;
如果学生不活跃,则在“学生”课程中使用的“ checkIsCurrent” api应提供错误的值。
以下是我的DTO课程。
/**
* A class representing a single student in a single class.
*/
public final class Student2 {
/**
* First name of the student.
*/
private final String firstName;
/**
* Whether the student is currently enrolled, or has already completed the
* course.
*/
private final boolean isCurrent;
/**
* Constructor.
* @param setFirstName Student first name
* @param setIsCurrent Student currently enrolled?
*/
public Student2(final String setFirstName,final boolean setIsCurrent) {
this.firstName = setFirstName;
this.isCurrent = setIsCurrent;
}
/**
* Get the first name of this student.
* @return The student's first name.
*/
public String getFirstName() {
return firstName;
}
/**
* Check if this student is active, or has taken the course in the past.
* @return true if the student is currently enrolled, false otherwise
*/
public boolean checkIsCurrent() {
return isCurrent;
}
}
现在我想知道最不活跃的学生的名字吗?
我要使用并行流来执行此操作?
public String mostCommonFirstNameOfInactiveStudentsParallelStream(final Student[] studentArray) {
try{
return Stream.of(studentArray)
.parallel()
.filter(s->!s.checkIsCurrent())
.map(s->s.getFirstName())
}
catch(Exception e){
throw e;
}
}
为此,并行流代码是什么?
最佳答案
您应该确定您的班级是Student
还是Student2
。此外,请勿插入任意的try … catch
块。
实现目标的一种方法是
public String mostCommonFirstNameOfInactiveStudentsParallelStream(Student2[] studentArray){
return Arrays.stream(studentArray)
.parallel()
.filter(s->!s.checkIsCurrent())
.collect(Collectors.toMap(Student2::getFirstName, s -> 1, Integer::sum))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
}
替代方法是
public String mostCommonFirstNameOfInactiveStudentsParallelStream(Student2[] studentArray){
return Arrays.stream(studentArray)
.parallel()
.filter(s->!s.checkIsCurrent())
.collect(Collectors.groupingByConcurrent(Student2::getFirstName,
Collectors.summingInt(s -> 1)))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
}
哪个更快,取决于几种情况。您也可以将
toMap
替换为toConcurrentMap
或将groupingByConcurrent
替换为groupingBy
,最后得到四个可供选择的测试方法。但是最有可能的是,顺序流总比并行流快,因为您不太可能拥有如此多的对象,因此并行处理会获得回报。