Java stream 的一些使用场景

49 阅读1分钟

根据条件分割 - 根据判断条件分割数组

适用于一些判断条件的切割,比如 a<100, type == 3 ,a != null 等

public class StreamGrouping {
    public static void main(String[] args) {
        List<String> data = Arrays.asList("a", "bb", "ccc", "dddd", "eeeee");
        
        // 使用 partitioningBy 根据条件分组
        Map<Boolean, List<String>> groups = data.stream()
            .collect(Collectors.partitioningBy(s -> s.length() > 3));
        // 满足条件的组
        List<String> groupTrue = groups.get(true);
        // 不满足条件的组
        List<String> groupFalse = groups.get(false); 
        // [dddd, eeeee]
        System.out.println("长度 > 3: " + groupTrue); 
        // [a, bb, ccc]
        System.out.println("长度 <= 3: " + groupFalse); 
    }
}

获取最大值

public class MaxTimeExample {
    public static void main(String[] args) {
        List<LocalDateTime> times = Arrays.asList(
            LocalDateTime.of(2023, 1, 1, 10, 0),
            LocalDateTime.of(2023, 1, 2, 12, 30),
            LocalDateTime.of(2023, 1, 1, 8, 45)
        );

        // 方法1: 使用自然排序(LocalDateTime实现了Comparable)
        Optional<LocalDateTime> maxTime = times.stream()
            .max(Comparator.naturalOrder());

        // 方法2: 直接使用max()(无参,但需要元素实现Comparable)
        // Optional<LocalDateTime> maxTime = times.stream().max();
        // 输出: 2023-01-02T12:30
        maxTime.ifPresent(System.out::println); 
    }
}