1. public class StreamApi {
    2. public static void main(String[] args) {
    3. List<Integer> list = Arrays.asList(4, 5, 3, 3, 2, 1);
    4. // forEach 遍历
    5. list.stream().forEach(e-> {
    6. System.out.println(e);
    7. });
    8. // 更简便的写法
    9. list.stream().forEach(System.out::println);
    10. // map:用于映射每个元素到对应的结果
    11. List<Integer> mapCollect = list.stream().map(e -> {
    12. return e * 2;
    13. }).collect(Collectors.toList());
    14. // filter:通过自定义过滤条件获取过滤元素
    15. List<Integer> filterCollect = list.stream().filter(e -> {
    16. return e % 2 == 0;
    17. }).collect(Collectors.toList());
    18. // sorted:通过定义排序规则对集合进行排序
    19. List<Integer> sortCollect = list.stream().sorted((e1, e2) -> {
    20. return e2 - e1;
    21. }).collect(Collectors.toList());
    22. // distinct:去重,使用 equals 方法判断是否相同
    23. List<Integer> distinctCollect = list.stream().distinct().collect(Collectors.toList());
    24. // limit:返回 n 个元素
    25. List<Integer> limitCollect = list.stream().limit(2).collect(Collectors.toList());
    26. // skip:跳过 n 个元素之后再输出
    27. List<Integer> skipCollect = list.stream().skip(2).collect(Collectors.toList());
    28. // allMatch:用于检测是否全部参数都满足条件
    29. boolean allMatchRes = list.stream().allMatch(e -> {
    30. return e > 0;
    31. });
    32. // anyMatch:用于检测是否存在一个或多个元素满足条件
    33. boolean anyMatchRes = list.stream().allMatch(e -> {
    34. return e % 2 == 0;
    35. });
    36. // noneMatch:用于检测是否不存在满足条件的元素
    37. boolean noneMatchRes = list.stream().noneMatch(e -> {
    38. return e > 100;
    39. });
    40. // 用于返回流中的第一个元素
    41. Integer findFirstRes = list.stream().filter(e -> e % 2 == 0).findFirst().get();
    42. // counting:计算元素总数
    43. long count = list.stream().count();
    44. Long countOfCollect = list.stream().collect(Collectors.counting());
    45. // maxBy:获取最大值,minBy:获取最小值
    46. Integer maxOfMaxBy = list.stream().collect(Collectors.maxBy((e1, e2) -> e1 - e2)).get();
    47. // averagingInt:计算平均值
    48. Double averagingIntRes = list.stream().collect(Collectors.averagingInt(Integer::intValue));
    49. // 字符串拼接
    50. String collectRes = list.stream().map(e -> e + "").collect(Collectors.joining(", "));
    51. }
    52. }