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

使用Java Stream筛选出现次数等于自身值的元素

解决思路与代码优化

首先你现有代码里的Collectors.counting()返回的是Long类型,强制转换Map<Integer, Integer>会引发类型转换异常,得先修正这个问题。接下来可以通过Stream链式调用,一步完成频率统计和条件筛选。

方案一:修正现有方法并后续筛选

先修正频率统计方法,确保类型匹配:

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5, 5);
        // 先统计频率,再筛选符合条件的元素
        Map<Integer, Integer> frequencyMap = getFrequencyMap(numbers.stream());
        List<Integer> result = frequencyMap.entrySet()
                .stream()
                .filter(entry -> entry.getKey().equals(entry.getValue()))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        System.out.println(result); // 输出 [1, 2, 5]
    }

    public static Map<Integer, Integer> getFrequencyMap(java.util.stream.Stream<Integer> elements) {
        // 用summingInt替代counting,直接得到Integer类型的计数
        return elements.collect(Collectors.groupingBy(
                Function.identity(),
                HashMap::new,
                Collectors.summingInt(e -> 1)
        ));
    }
}

方案二:合并为单条Stream链(更简洁)

不需要单独的频率统计方法,直接用Stream完成所有操作:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5, 5);
        
        List<Integer> result = numbers.stream()
                // 按元素分组并统计次数,得到Map<Integer, Long>
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                // 筛选元素值等于出现次数的条目,注意counting返回Long,需转成Integer比较
                .filter(entry -> entry.getKey().equals(entry.getValue().intValue()))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        
        System.out.println(result); // 输出 [1, 2, 5]
    }
}

关键说明

  • Collectors.counting()返回Long类型,比较时需要调用intValue()转成Integer,或者用Collectors.summingInt(e -> 1)直接得到Integer类型的计数,避免类型不匹配问题。
  • 通过entrySet().stream()将Map的键值对转为Stream,再用filter筛选符合键 == 值的条目,最后提取键收集成结果集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:39:56