可以直接复制过去参照注释理解一下
然后可以自己敲一遍熟悉一下
package com.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("laoliaaa","lilili","suiyi","niuniusa","wo","nishi");
List<Integer> list2 = Arrays.asList(110,227,112,221,221);
// 创建顺序流
Stream<String> stream = list.stream();
Stream<Integer> stream2 = list2.stream();
// 过滤元素并且打印
stream.filter(arg -> arg == "suiyi").forEach(System.out::println);
// 映射每个元素对应结果也就是处理元素
System.out.print("处理元素:");
stream2.map(num -> ++num).forEach(f -> System.out.print(f+","));
System.out.println();
// 保留前几个元素
System.out.print("保留元素:");
list2.stream().limit(3).forEach(f -> System.out.print(f+","));
System.out.println();
// 丢掉前几个元素
System.out.print("丢掉元素还剩:");
list2.stream().skip(3).forEach(f -> System.out.print(f+","));
System.out.println();
// 对流排序
System.out.print("排序之后:");
list2.stream().sorted().forEach(f -> System.out.print(f+","));
System.out.println();
// 对流去重复
System.out.print("去重还剩:");
list2.stream().distinct().forEach(f -> System.out.print(f+","));
System.out.println();
// 综合使用
System.out.print("综合使用:");
list.stream().filter(arg -> arg.length() > 4).map(String::length).sorted().limit(2).forEach(f -> System.out.print(f+","));
System.out.println();
// 统计个数
System.out.print("list2元素个数:");
System.out.print(list2.stream().count());
System.out.println();
// 归约将元素汇总成结果
System.out.print("归约结果:");
list = list.stream().filter(arg -> arg.length() > 2).collect(Collectors.toList());
System.out.print(list);
System.out.println();
}
}
运行结果
suiyi
处理元素:111,228,113,222,222,
保留元素:110,227,112,
丢掉元素还剩:221,221,
排序之后:110,112,221,221,227,
去重还剩:110,227,112,221,
综合使用:5,5,
list2元素个数:5
归约结果:[laoliaaa, lilili, suiyi, niuniusa, nishi]