java集合stream操作

forEach - 遍历

Stream<Integer> stream = Stream.of(2, 3, 1, 4);
stream.forEach(System.out::println);

filter - 过滤

Stream<Integer> stream = Stream.of(2, 3, 1, 4);
Stream<Integer> newStream = stream.filter(num -> num > 2);
System.out.print("过滤之后:");
newStream.forEach(x -> System.out.print(x + " "));

map - 转换

Stream<Integer> stream = Stream.of(2, 3, 1, 4);
Stream<Integer> newStream = stream.map(num -> num + 1);
newStream.forEach(System.out::println);

peek

该方法可以对流中的每一个元素进行操作,返回新的流.

Dog[] dogs = {new Dog("Tom", 1), new Dog("Jie", 2)};
Stream<Dog> dogStream = Arrays.stream(dogs);
Stream<Dog> newDogStream = dogStream.peek(dog -> dog.age = 999);
newDogStream.forEach(System.out::println);

flatMap

该方法产生一个流,它是通过将传入lambda表达式应用于当前流中所有元素所产生的结果连接到一起而获得的。(注意,这里的每个结果都是一个流。)

List<Stream<Integer>> streamList = new ArrayList<>();
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream<Integer> stream3 = Stream.of(7, 8, 9);
streamList.add(stream1);
streamList.add(stream2);
streamList.add(stream3);

Stream<Stream<Integer>> stream = streamList.stream();
// flatMap里面的lambda表达式应当返回一个流
Stream<Integer> integerStream = stream.flatMap(x -> x);
integerStream.forEach(System.out::println);

limit和skip方法

limit方法可以对流进行裁剪,只取前n个流,skip方法则是跳过前n个流

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> newStream = stream.limit(4);
newStream.forEach(System.out::println);

// 要避免skip传入的值为负数
newStream.skip(Math.max(list.size() - 3, 0))

distinct - 去重

Stream<Integer> stream = Stream.of(1, 2, 3, 3, 1, 4);
Stream<Integer> newStream = stream.distinct();
newStream.forEach(System.out::println);

sorted - 排序

Stream<Integer> stream = Stream.of(4, 1, 3, 2);
Stream<Integer> newStream = stream.sorted();
newStream.forEach(System.out::println);

toArray - 转数组

Stream<String> namesStream = Stream.of("tom", "luck", "jerry");
String[] names = namesStream.toArray(String[]::new);
System.out.println(Arrays.toString(names));

collect

收集到集合

List<Integer> list = nums.stream().collect(Collectors.toList());
Set<Integer> set = nums.stream().collect(Collectors.toSet());
TreeSet<Integer> treeSet = nums.stream().collect(Collectors.toCollection(TreeSet::new));

toMap

需要注意key不能重复

Stream<String> namesStream = Stream.of("tom", "jack", "lucy");
Map<Character, String> namesMap = namesStream
        .collect(Collectors
                .toMap(k -> k.charAt(0), v -> v.toUpperCase()));
System.out.println(namesMap);
posted @ 2023-12-25 11:27  itwetouch  阅读(37)  评论(0编辑  收藏  举报