您的位置:首页 > 编程语言 > Java开发

java8中的Stream

2015-06-15 12:03 627 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: