Stream流操作

Stream流

Stream 中文称为 “流”,通过将集合转换为这么一种叫做 “流” 的元素序列,通过声明性方式,能够对集合中的每个元素进行一系列并行或串行的流水线操作。

函数式编程带来的好处尤为明显。这种代码更多地表达了业务逻辑的意图,而不是它的实现机制。易读的代码也易于维护、更可靠、更不容易出错。

例:查找list重复元素

    public static void main(String[] args) {
        CardVo c1 = new CardVo();
        c1.setInCardNo("a");
        CardVo c2 = new CardVo();
        c2.setInCardNo("b");
        CardVo c3 = new CardVo();
        c3.setInCardNo("c");
        CardVo c4 = new CardVo();
        c4.setInCardNo("a");

        List<CardVo> list = new ArrayList<>();
        list.add(c1);
        list.add(c2);
        list.add(c3);
        list.add(c4);

        //查找list重复元素
        List<String> nos = list.stream()
                .map(CardVo::getInCardNo)
                .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))
                .entrySet()
                .stream()
                .filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        System.out.println(nos);
    }
    public static <T> List<T> getDuplicateElements(List<T> list) {
        return list.stream()
                .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
                .entrySet().stream() // Set<Entry>转换为Stream<Entry>
                .filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
                .map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
                .collect(Collectors.toList()); // 转化为 List
    }
Set<String> set = list.stream().filter(i -> list.stream().filter(i::equals).count() > 1).collect(Collectors.toSet());
原文地址:https://www.cnblogs.com/xiaomaoyvtou/p/14202968.html