1. 随机获得流中任意Item

@Test
public void testFindAny() {
    Integer integer = Stream.of(1, 2, 3)
            // .parallel()
            .findAny()
            .get();

    System.out.println(integer);
}

⚠️ 首先Stream#findAny()返回的是一个Optional, 请在实际用途中不要直接GET

2. 获得的流中第一个Item

@Test
public void testFindFirst() {
    Integer integer = Stream.of(1, 2, 3)
             .parallel()
            .findFirst()
            .get();

    System.out.println(integer);
}

⚠️ 首先如果不开parallel()并行的话findAny 等同于 findFirst

3. 排序

@Test
public void testSort() {
    List<Integer> list = Stream.of(3, 2, 1)
            .sorted()
            .collect(Collectors.toList());

    System.out.println(list);
}

// result: [1, 2, 3]

4. 分组操作

@Test
public void testGroup() {
    // 这里是将自身分组
    Map<Integer, List<Integer>> group = Stream.of(3, 2, 1, 2, 1, 2, 3, 4)
            .collect(Collectors.groupingBy(Function.identity()));
    System.out.println(group);
    
    // result: {1=[1, 1], 2=[2, 2, 2], 3=[3, 3], 4=[4]}

    // 这里是将自身分组, 并统计的出现次数
    Map<Integer, Long> group2 = Stream.of(3, 2, 1, 2, 1, 2, 3, 4)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    System.out.println(group2);
    
    // result: {1=2, 2=3, 3=2, 4=1}
}

5. 去重

5.1 利用toSet去重

@Test
public void toSetDistinct() {
    Set<Integer> collect = Stream.of(3, 2, 1, 2, 1, 2, 3, 4)
            .collect(Collectors.toSet());

    System.out.println(collect);

    // result: [1, 2, 3, 4]
}

5.2 利用Stream#distinct()去重

@Test
public void testDistinct() {

    List<Integer> list = Stream.of(3, 2, 1, 2, 1, 2, 3, 4)
            .distinct()
            .collect(Collectors.toList());

    System.out.println(list);


    // result: [3, 2, 1, 4]
}