ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스트림(2) - 중간 처리
    언어/JAVA 2023. 7. 14. 14:46

     

    1. 요소 걸러내기(필터링)

     

    - 필터링을 위한 메서드는 distinct()와 filter()가 있다.

    출처: 이것이 자바다

       - distinct()는 요소의 중복을 제거한다.

          >객체 스트림의 경우 equals메소드를 기준으로 판단한다.

          > IntStream,LongStream 등은 값의 중복을 제거한다.

     

      - filter()는 매개값인 Predicate가 true인 요소만 리턴한다.

        Predicate는 IntPredicate,LongPredicate,DoublePredicate등이 있다. (함수형 인터페이스임) 

         (매개변수로 주어진 값을  통해 조건검사 - true나 false를 리턴하도록 람다식을 짜)[test()메서드]

     

    2. 요소 변환(매핑)

     

    -매핑은 스트림을 다른 요소로 변환하는 중간 처리 기능을 한다.

    - mapXXX(), asDoubleStream(),asLongStream(),boxed,flatMapXxx()등이 있다.

    출처: 이것이 자바다

    List<Student> studentList = new ArrayList<>();
    studentList.add(new Student("장",85));
    studentList.add(new Student("장",11));
    studentList.add(new Student("장",22));
    
    studentList.map(student -> student.getScore()).forEach(score -> System.out.println(score));

     

    기본형 <-> 기본형 , 기본형 <->래퍼클래스간 변환

    출처: 이것이 자바다

     

    //스트림 통으로 변환
    intStream.asDoubleStream().//
    intStream.boxed().//

     

    2.1 요소를 복수개의 요소로 변환

     

    - flatMapXXX메서드는 하나의 요소를 복수개의 요소들로 변환한 새로운 스트림을 리턴한다.

    출처: 이것이 자바다

    *Function 인터페이스 인것은 동일함! 새로운 스트림을 반환하도록 하면됨 (컬렉션이나 배열에 스트림 생성 메서드 호출)

     

    List<String> list1 = new ArrayList<>();
    list1.add("s s s s");
    list1.add("a dads ds)";
    list1.stream.flatMap(string -> Arrays.stream(string.split(" ")).//
    
    //"s s s s", "a dads ds" -> 위와 같던 스트림을
    //"s","s","s","s","a","dads","ds" ->이렇게 변환
    
    List<String> list2 = Arrays.asList("10, 20, 30","40, 50");
    
    list2.stream().flatMap(string -> {
       String[] temp = string.split(", ");
       int[] tempIntArr = new int[temp.lenght];
       
       for(int i=0 ; i<temp.length;i++){
       	 tempIntArr[i] = Integer.parseInt(temp[i]);
       }
       return Arrays.stream(tempIntArr);
    }).//

     

     

    3. 요소 정렬 

     

    - 정렬은 요소를 오름차순 또는 내림차순으로 정렬한다.

    출처: 이것이 자바다.

    3.1 Comparable 구현객체의 정렬

     

    - 스트림의 요소가 Comparable을 구현하고 있어야만, sorted()메서드를 작동시킬 수 있다.

    - 만약 내림차순으로 정렬하고 싶다면, Comparator.reverseOrder()메소드가 리턴하는 Comparator을 매개값으로 제공하자.

     

    3.2 Comparator를 이용한 정렬

     

    - 요소 객체가 Comparable을 구현하고 있지 않다면, 비교자를 제공하자.

    - 비교자는 Comparator은 인터페이스를 구현한 객체(클래스)의미 -> 람다식으로 대체 

    sort((o1,o2)->{...}))
    //o1이 o2보다 작으면 음수, 같으면 0, 크면 양수 리턴하도록 작성하자 
    //o1,o2가 정수일 경우에는 Integer.compare()등을 호출하면 편하다.
    List<Student> stlist= new ArrayList<>();
    stlit.add(new Student("얍",30));
    stlit.add(new Student("얍",20));
    stlit.add(new Student("얍",10));
    
    stlist.stream().sorted((o1,o2)->Integer.compare(o1.getScore(), o2.getScore()))..//

     

    4. 요소를 하나씩 처리(루핑)

     

    - 루핑은 요소를 하나씩 반복해서 가져와 처리하는 것을 말한다.

    - 중간처리 peek()와 forEach()가 있다.

    - 매개타입은 Consumer이다. (리턴값이 없음)

     

    출처: 이것이자바다

     

     

    참고자료: 이것이 자바다 

Designed by Tistory.