zoukankan      html  css  js  c++  java
  • java8中的Stream

    Collection.stream() / parallelStream()

    1. Stream

    1)Filter

       stringCollection .stream().filter((s) -> s.startsWith("a")) .forEach(System.out::println); 

    2)Sorted

      stringCollection .stream().sorted()

    3)Map

      stringCollection .stream().map(String::toUpperCase) .sorted((a, b) -> b.compareTo(a)) 

    4)Matches

    boolean anyStartsWithA = stringCollection.stream().anyMatch((s) -> s.startsWith("a"));

    boolean allStartsWithA = stringCollection.stream().allMatch((s) -> s.startsWith("a"));

    boolean noneStartsWithZ = stringCollection.stream().noneMatch((s) -> s.startsWith("z"));

    5)Count 

    long startsWithB = stringCollection.stream().filter((s) -> s.startsWith("b")) .count(); 
    6)Reduce
    stringCollection .stream().sorted().reduce((s1, s2) -> s1 + "#" + s2); 
     
    2. Parallel stream
    1) sorted
        long t0 = System.nanoTime();

        long count = values.parallelStream().sorted().count(); System.out.println(count);

        long t1 = System.nanoTime();

        long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("parallel sort took: %d ms", millis)); // parallel sort took: 472 ms 

    2) MAP

    Map<Integer, String> map = new HashMap<>();

    for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i);}

    map.forEach((id, val) -> System.out.println(val)); 

    map.computeIfPresent(3, (num, val) -> val + num); map.get(3); // val33

    map.computeIfPresent(9, (num, val) -> null); map.containsKey(9); // false

    map.computeIfAbsent(23, num -> "val" + num); map.containsKey(23); // true

    map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33 

    map.getOrDefault(42, "not found"); // not found 

    map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); map.get(9); // val9
    map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); map.get(9); // val9concat 
  • 相关阅读:
    安装、升级pip,但是python -m pip install --upgrade pip报错
    架构即未来阅读笔记3
    第十二周学习总结
    《大型网站技术架构:核心原理与案分析》阅读笔记02
    2021寒假(12)
    2021寒假(10)
    Spark简介
    《大型网站技术架构:核心原理与案分析》阅读笔记01
    2021寒假(9)
    2021寒假(8)
  • 原文地址:https://www.cnblogs.com/feika/p/4576794.html
Copyright © 2011-2022 走看看