You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java并行流查找非活跃学生的最常见名字?

如何用并行流找出非活跃学生的最常见名字?

我有一个Student类的数组,Student类包含私有final字段firstName和isCurrent,还有一个checkIsCurrent()方法在学生非活跃时返回false。对应的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;
    }
}

请问完整的并行流实现代码应该是什么?


要实现这个需求,我们需要在并行流中完成名字频率统计和找出最高频名字两个核心步骤。这里推荐使用并发安全的收集器来适配并行流的特性,提升效率。以下是完整的实现代码:

import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public String mostCommonFirstNameOfInactiveStudentsParallelStream(final Student[] studentArray) {
    try {
        return Stream.of(studentArray)
                .parallel()
                // 过滤出非活跃学生
                .filter(student -> !student.checkIsCurrent())
                // 提取学生名字
                .map(Student::getFirstName)
                // 并行统计每个名字的出现次数,用并发收集器适配并行流
                .collect(Collectors.groupingByConcurrent(
                        String::valueOf,
                        Collectors.counting()
                ))
                // 将统计结果转为流,找出出现次数最多的名字
                .entrySet()
                .stream()
                .max(Map.Entry.comparingByValue())
                // 存在最高频名字则返回,无匹配时返回null(也可按需抛出异常)
                .map(Map.Entry::getKey)
                .orElse(null);
    } catch (Exception e) {
        // 可根据业务需求添加自定义异常处理,比如包装为特定业务异常
        throw e;
    }
}

代码细节说明:

  1. 并行流适配:Stream.of(studentArray).parallel() 把数组转为并行流,利用多线程加速数据处理,适合大数据量场景。
  2. 非活跃学生过滤:filter(student -> !student.checkIsCurrent()) 精准筛选出目标学生群体。
  3. 名字提取:map(Student::getFirstName) 将Student对象转换为名字字符串,简化后续统计逻辑。
  4. 并发频率统计:Collectors.groupingByConcurrent() 是并行流友好的收集器,相比普通groupingBy能避免不必要的线程同步开销,高效生成ConcurrentMap<String, Long>类型的名字-次数映射。
  5. 最高频名字获取:通过max(Map.Entry.comparingByValue())找到次数最多的名字条目,再提取对应的名字;orElse(null)处理无匹配学生的边界情况。

额外注意点:

  • 如果有多个名字出现次数相同,并行流下max会返回第一个遇到的高频名字(顺序不固定)。若需要处理平局,可自定义比较逻辑,比如按名字字典序选择。
  • 若学生数组规模很小,并行流的线程开销可能抵消效率优势,此时使用普通串行流会更合适。

内容的提问来源于stack exchange,提问作者user752590

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:46:50