Java Stream Examples

Byul·2023년 6월 9일

Java

목록 보기
2/10
        // IntStream, filter, reduce
        List<Integer> numbers = IntStream.range(1, 11).boxed().collect(Collectors.toList());
        System.out.println(numbers.stream().filter(number -> number % 2 == 0).collect(Collectors.toList()));
        System.out.println(numbers.stream().reduce((acc, cur) -> acc + cur));
        System.out.println(numbers.stream().reduce(0, Integer::sum));

        // map, joining
        List<String> names = Arrays.asList("Byul", "Han", "Kang");
        System.out.println(names.stream().map(name -> name.length()).collect(Collectors.toList()));
        System.out.println(names.stream().map(String::length).collect(Collectors.toList()));
        names.forEach(System.out::println);
        System.out.println(names.stream().collect(Collectors.joining(", ")));

        // distinct
        numbers.addAll(0, numbers);
        System.out.println(numbers);
        System.out.println(numbers = numbers.stream().distinct().collect(Collectors.toList()));

        // sorted
        Collections.shuffle(numbers);
        System.out.println(numbers);
        System.out.println(numbers.stream().sorted().collect(Collectors.toList()));
profile
junior backend developer

0개의 댓글