박서희연구소

[Java] Stream 본문

○ Programming [Basic]/Java

[Java] Stream

SEOHUI PARK 2022. 9. 6. 12:51
반응형

1. Stream 이란?

Object 의 Collection 처리를 위해 Java 8 의 주요 기능으로 java.util.stream 이 도입되었다.

주요 API 로 Stream<T> 가 있다.

기대 효과로 Stream데이터 구조를 변경하지 않고, 파이프라인 방식에 따라 결과만을 제공한다.

 

2. 왜 사용하나?

  • Stream 은 데이터 소스를 감싸는 wrapper 이므로, 해당 데이터 소스로 작업할 수 있으며, 편하고 빠르게 대량 처리가 가능
  • 데이터를 저장하지 않기에 데이터 구조가 아니며, 데이터 소스를 수정하지 않음

3. 내가 활용해 본 Stream

public void streamExample() {
    List<Integer> integerList = Arrays.asList(1, 1, 11, 11, 21, 21, 31, 31);

    integerList.stream().distinct().forEach(i -> System.out.println(i));
    integerList.stream().limit(3).forEach(i -> System.out.println(i));

    List<String> stringList = Arrays.asList("1", "2", "3");

    List<Integer> integerList2 = stringList.stream().map(s -> Integer.valueOf(s)).toList();

    System.out.println(integerList2);

    List<Student> studentList = Arrays.asList(
            new Student(1, "Seohui Park"),
            new Student(2, "Steve"),
            new Student(3, "David")
    );

    List<String> nameList = studentList.stream().map(s -> s.getName()).collect(Collectors.toList());

    System.out.println(nameList);

    List<String> stringList2 = Arrays.asList("a", "", "b", "", "c");

    Long count = stringList2.stream().filter(s -> s.isEmpty()).count();

    System.out.println(count);

    Random random = new Random();
    random.ints().limit(5).sorted().forEach(r -> System.out.println(r));
}

결과

- 끝 -

반응형

'○ Programming [Basic] > Java' 카테고리의 다른 글

[Java] List  (0) 2022.12.26
[Java] Optional  (0) 2022.09.05
[Java] Lambda Expression  (0) 2022.09.05
[Java] EnumSet  (0) 2022.09.02
[Java] 객체 지향 프로그래밍[OOP(Object-Oriented Programming)] 이란?  (0) 2020.09.16
Comments