Kotlin-Demo/jTest/StreamTest.java

40 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package jTest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class StreamTest {
public static void main(String[] args) {
// 创建二维数组
List<List<String>> list1 = Arrays.asList(
Arrays.asList("a", "b", "c"),
Arrays.asList("a", "b", "c")
);
// 二维数组平整化
List<String> list = list1.stream().flatMap(List::stream).toList();
System.out.println(list);// [a, b, c, a, b, c]
// peek可以用来调试也可以塞对象不改变流如果你这个里面有对象比如xxx.setXXX() 那么也会修改这个对象
List<String> list2 = list.stream().filter(s -> s.startsWith("a"))
.peek(System.out::println)
.map(String::toUpperCase).toList();
System.out.println(list2);// [A, A]
// 求和
int sum = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).sum();
System.out.println(sum);
// Map集合
Map<String, Integer> counts = new HashMap<>();
counts.put("apple", 1);
counts.put("banana", 1);
System.out.println(counts);
counts.compute("apple", (key, val) -> val == null ? 1 : val + 1);
System.out.println(counts);
}
}