我有“学生”类(class)数组。学生类(class)有两个字段:
private final String firstName;
private final boolean isCurrent;
如果学生处于非事件状态,“学生”类中存在的“checkIsCurrent”API 将给出错误值。
以下是我的 DTO 类(class)。
/**
* 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;
}
}
并行流代码是什么?
最佳答案
您应该决定您的类(class)是 Student
还是 Student2
。此外,不要插入任意 try … catch
block 。
实现目标的一种方法是
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
,最终得到四种替代方案进行测试。
但无论如何,顺序流很可能比并行流更快,因为您不太可能拥有如此多的对象,因此并行处理会获得返回。
关于lambda - 通过 DTO 进行 lambda 表达式的流传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48147650/