개발

Stream 본문

Java

Stream

Dev.hs 2021. 3. 14. 19:33

요소 반복

public class Test {
    public static void main(String[] args) throws Exception {
        List<String> list = Arrays.asList("A","B","C","D");

        Stream<String> stream = list.stream();

        //람다식에서 파라미터가 하나일때 ()생략 가능.
        stream.forEach(element -> System.out.println(element));
    }
}

String -> Integer배열 반환 후(map이용) 평균값 구하기

public class Test {
    public static void main(String[] args) throws Exception {
        List<String> list = Arrays.asList("30","40","50","60","70");

        double avg = list.stream().mapToInt(e -> Integer.parseInt(e))
                     .average()
                     .getAsDouble();

        System.out.println("평균값 : " + avg);
    }
}

50보다 큰 숫자만 넘는 값만 필터링

public class Test {
    public static void main(String[] args) throws Exception {
        List<Integer> list = Arrays.asList(30,40,50,40,60,70);

        Stream<Integer> stream = list.stream()
                .filter(e -> e > 50);    //

        stream.forEach(e -> System.out.println(e));
    }
}

중복 요소 제거하기

public class Test {
    public static void main(String[] args) throws Exception {
        List<Integer> list = Arrays.asList(30,30,30);

        Stream<Integer> stream = list.stream()
                .distinct();

        stream.forEach(e -> System.out.println(e));
    }
}

오름차순 정렬하기

public class Test {
    public static void main(String[] args) throws Exception {
        List<Integer> list = Arrays.asList(100,90,30,40,50,40,60,70);
        //1
        Stream<Integer> stream = list.stream().sorted();
        //2
        Stream<Integer> stream = list.stream().sorted((a,b) -> a.compareTo(b));

        stream.forEach(e -> System.out.println(e));
    }
}

디폴트처리

public class Test {
    public static void main(String[] args) throws Exception {
        List<Integer> list = Arrays.asList(100,90,30,40,50,40,60,70);

        double a = list.stream()
                .mapToInt(i -> i)
                .filter(i -> i > 100)
                .average()
                .orElse(1000);

        System.out.println(a);    //1000
    }
}

 

'Java' 카테고리의 다른 글

Maven dependency가 겹칠경우  (0) 2022.01.09
ORACLE OPEN JPA에서 설정과 다른 schema의 db를 조회  (0) 2022.01.09
Class 클래스  (0) 2021.03.06
제네릭 기초  (0) 2021.03.06
자주쓰는 날짜 관련 api 정리 (yyyyMMddHHmmss)  (0) 2021.02.23
Comments