public class StreamApi { public static void main(String[] args) { List<Integer> list = Arrays.asList(4, 5, 3, 3, 2, 1); // forEach 遍历 list.stream().forEach(e-> { System.out.println(e); }); // 更简便的写法 list.stream().forEach(System.out::println); // map:用于映射每个元素到对应的结果 List<Integer> mapCollect = list.stream().map(e -> { return e * 2; }).collect(Collectors.toList()); // filter:通过自定义过滤条件获取过滤元素 List<Integer> filterCollect = list.stream().filter(e -> { return e % 2 == 0; }).collect(Collectors.toList()); // sorted:通过定义排序规则对集合进行排序 List<Integer> sortCollect = list.stream().sorted((e1, e2) -> { return e2 - e1; }).collect(Collectors.toList()); // distinct:去重,使用 equals 方法判断是否相同 List<Integer> distinctCollect = list.stream().distinct().collect(Collectors.toList()); // limit:返回 n 个元素 List<Integer> limitCollect = list.stream().limit(2).collect(Collectors.toList()); // skip:跳过 n 个元素之后再输出 List<Integer> skipCollect = list.stream().skip(2).collect(Collectors.toList()); // allMatch:用于检测是否全部参数都满足条件 boolean allMatchRes = list.stream().allMatch(e -> { return e > 0; }); // anyMatch:用于检测是否存在一个或多个元素满足条件 boolean anyMatchRes = list.stream().allMatch(e -> { return e % 2 == 0; }); // noneMatch:用于检测是否不存在满足条件的元素 boolean noneMatchRes = list.stream().noneMatch(e -> { return e > 100; }); // 用于返回流中的第一个元素 Integer findFirstRes = list.stream().filter(e -> e % 2 == 0).findFirst().get(); // counting:计算元素总数 long count = list.stream().count(); Long countOfCollect = list.stream().collect(Collectors.counting()); // maxBy:获取最大值,minBy:获取最小值 Integer maxOfMaxBy = list.stream().collect(Collectors.maxBy((e1, e2) -> e1 - e2)).get(); // averagingInt:计算平均值 Double averagingIntRes = list.stream().collect(Collectors.averagingInt(Integer::intValue)); // 字符串拼接 String collectRes = list.stream().map(e -> e + "").collect(Collectors.joining(", ")); }}