반응형

필터링(distinct, filter)

스트림 사용시 필터링 방법을 사용하여 데이터를 걸러낼 수 있습니다.

public static void main(String[] args) {
    List<String> names = Arrays.asList("홍길동", "신용권", "감자바", "신용권", "신민철");

    names.stream()
        .distinct()
        .forEach(n->System.out.println(n));
    System.out.println();

    names.stream()
        .filter(n->n.startsWith("신"))
        .forEach(n->System.out.println(n));
    System.out.println();

    names.stream()
        .distinct()
        .filter(n->n.startsWith("신"))
        .forEach(n->System.out.println(n));
}

첫번째는 distinct()함수를 통해서 중복을 제거 하였습니다.

두번째는 filter() 함수를 통해서 신으로 시작하는 값만 필터링 하였으며, 세번째는 중복을 제거 하고 필터링을 적용 하였습니다.

매핑(map)

매핑은 스트림의 요소들을 다른 요소로 대체를 합니다.

 

flatMap()

public static void main(String[] args) {
    List<String> inputList1 = Arrays.asList("java8 lambda", "stream mapping");

    inputList1.stream()
            .flatMap(data -> Arrays.stream(data.split(" ")))
            .forEach(word -> System.out.println(word));
    System.out.println();
}

List<String>이 있습니다. List<Sgring>을 flatMap을 활용하여 Stream<String> 요소로 대체를 하였습니다.

Arrays.Stream()을 사용하면 Stream<String>이 만들어지고, 이 값이 flatMap을 통해서 하나의 Stream<String>으로 리턴이되겠습니다.

String 스트림을 다시 forEach를 활용하여 출력하는 모습입니다.

flatMapToInt()

public static void main(String[] args) {
    List<String> inputList2 = Arrays.asList("10, 20, 30", "40, 50, 60");

    inputList2.stream()
            .flatMapToInt(data -> {
                String[] strArray = data.split(",");
                int[] intArr = new int[strArray.length];
                for (int i = 0; i < strArray.length; i++) {
                    intArr[i] = Integer.parseInt(strArray[i].trim());
                }
                return Arrays.stream(intArr);
            })
            .forEach(number -> System.out.println(number));
}

List<String>타입을 flatMapToInt()을 활용하여 int 타입의 스트림으로 변경하였습니다.

 

mapToInt()

public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(
        new Student("홍길동", 10),
        new Student("신용권", 20),
        new Student("유미선", 30)
    );

    studentList.stream()
        .mapToInt(Student::getScore)
        .forEach(score->System.out.println(score));
}

mapToInt를 활용하여 기존의 List<Student> 리스트를 IntStream으로 만들어 주고 있습니다.

 

flatMap()과 mapTo()의 차이점은 flatMap은 기존의 요소를 평평하게 펴주는 역할을 합니다. 하지만 mapTo()는 새로운 요소로 만들어 줍니다.

 

asDoubleStream()과 boxed() 메소드

public static void main(String[] args) {
    int[] intArray = {1, 2, 3, 4, 5};

    IntStream intStream = Arrays.stream(intArray);
    intStream.asDoubleStream().forEach(d->System.out.println(d));

    System.out.println();

    intStream = Arrays.stream(intArray);
    intStream.boxed().forEach(obj->System.out.println(obj.intValue()));
}

asDoubleStream()을 활용하여 int 타입을 double타입의 DoubleStream을 생성하였습니다.

boxed() 메소드를 활용하여 Stream<Integer> 타입을 생성.

 

참고 책)

이것이 자바다 (신용권의 Java 프로그래밍 정복)

반응형

+ Recent posts