java8中的Stream

java

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 

以上是 java8中的Stream 的全部内容, 来源链接: utcz.com/z/390490.html

回到顶部