• 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());
  • 相关阅读:
    hdu1150&&POJ1325 Machine Schedule---最小点覆盖
    hdu-1068&&POJ1466 Girls and Boys---最大独立集
    hdu-2680 Choose the best route---dijkstra+反向存图或者建立超级源点
    hdu-1317 XYZZY---Floyd判连通+bellman最短路
    hdu-1874 畅通工程续---模板题
    hdu-2112 HDU Today---dijkstra+标号
    hdu-2066 一个人的旅行---模板题
    hdu-3790 最短路径问题---dijkstra两重权值
    hdu-2544 最短路---模板题
    BZOJ3529: [Sdoi2014]数表
  • 原文地址:https://www.cnblogs.com/xiaomaoyvtou/p/14202968.html
Copyright © 2020-2023  润新知