创建Stream的4种方式
@Test
public void test1() {
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream();
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
}
过滤和截取
@Test
public void test2() {
Integer[] nums = new Integer[]{3, 1, 10, 5, 2, 6};
Stream<Integer> stream = Arrays.stream(nums);
stream.filter((x) -> x > 2).limit(2).forEach(System.out::println);
}
映射
@Test
public void test3() {
String[] strs = new String[]{"aa", "bb"};
Stream<String> stream = Arrays.stream(strs);
stream.map(x -> x + "Mock").forEach(System.out::println);
Stream<Stream<Character>> streamStream = stream.map(x -> getCharacter(x));
streamStream.forEach(x -> x.forEach(System.out::println));
Stream<Character> characterStream = stream.flatMap(x -> getCharacter(x));
}
private Stream<Character> getCharacter(String str) {
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()) {
list.add(ch);
}
return list.stream();
}
排序
@Test
public void test4() {
Arrays.asList("c", "a", "b").stream().sorted((x, y) -> x.compareTo(y)).forEach(System.out::println);
Map<String, String> map = new HashMap<>();
map.put("c", "c");
map.put("a", "a");
map.put("b", "b");
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(x -> System.out.println(x.getKey()));
}
查找与匹配
@Test
public void test5() {
Arrays.asList("c", "a", "b").stream().allMatch(x -> "a".equals(x));
Optional<String> any = Arrays.asList("c", "a", "b").stream().findAny();
Optional<String> max = Arrays.asList("c", "a", "b").stream().max((x, y) -> x.compareTo(y));
}
收集
@Test
public void test6() {
Integer[] num = new Integer[]{4, 5, 2, 3};
Integer sum = Arrays.asList(num).stream().reduce(0, (x, y) -> x + y);
Integer sum2 = Arrays.asList(num).stream().reduce(0, Integer::sum);
ArrayList<Integer> collect = Arrays.asList(new Integer[]{4, 5, 2, 3})
.stream().map(x -> x + 1).collect(Collectors.toCollection(ArrayList::new));
List<Integer> collect1 = Arrays.asList(new Integer[]{4, 5, 2, 3})
.stream().map(x -> x + 1).collect(Collectors.toList());
Long cout = Arrays.asList(new Integer[]{4, 5, 2, 3})
.stream().collect(Collectors.counting());
Double avg = Arrays.asList(new Integer[]{4, 5, 2, 3})
.stream().collect(Collectors.averagingInt(x -> x));
Optional<Integer> max = Arrays.asList(new Integer[]{4, 5, 2, 3}).stream()
.collect(Collectors.maxBy((x, y) -> x.compareTo(y)));
System.out.println(max.get());
}