Stream API 사용을 위해서는 먼저 Stream을 생성해주어야 한다.
타입에 따라 Stream을 생성하는 방법이 다르다.
그 중 Collection과 Array에 대한 생성 방법을 알아보자.
Collection 인터페이스에는 stream()
이 정의되어 있다.
따라서 List, Set 등의 객체들은 모두 stream()으로 생성할 수 있다.
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> listStream = list.stream();
Stream의 of()
메소드 혹은 Arrays의 stream()
메소드를 사용한다.
Stream<String> stream = Stream.of("a", "b", "c");
Stream<String> stream = Stream.of(new String[] {"a", "b", "c"});
Stream<String> stream = Arrays.stream(new String[] {"a", "b", "c"});
Stream<String> stream = Arrays.stream(new String[] {"a", "b", "c"}, 0, 3);
필터링, 말그대로 조건과 일치하는 데이터만을 정제한다.
람다식과의 궁합이 좋다.
List<String> myList = Arrays.asList("minsu", "minji", "youngsu");
Stream<String> stream = myList.stream().filter(name -> name.contains("m"));
말 그대로 기존의 Stream 요소 하나하나를 매핑하여 새로운 Stream을 형성한다.
map(c -> c.toUpperCase())
대문자로 변경하는 코드
map(s -> s.length())
문자열의 길이를 나타내는 코드
Stream의 요소들을 정렬한다.
sorted()
오름차순 정렬
sorted(Comparator.reverseOrder())
내림차순 정렬
중복된 데이터가 존재하는 경우 중복을 제거한다.
distinct()는 Object의 equals() 메소드를 사용한다.
클래스를 Stream으로 사용한다면 equals와 hashCode를 오버라이드 해야만 distinct()가 적용된다.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
Stream의 결과에 영향을 미치지 않고 특정 연산을 수행한다.
중간에 출력하고 싶을 때 유용하게 쓰인다.
int sum = IntStream.of(1, 3, 5, 7, 9)
.peek(System.out::println)
.sum();
요소들을 List나 Set, Map 등 다른 종류의 결과로 수집하고 싶은 경우 사용한다.
형태 : Object collect(Collector collector)
List<Product> productList = Arrays.asList(
new Product(23, "potatoes"),
new Product(14, "orange"),
new Product(13, "lemon"),
new Product(23, "bread"),
new Product(13, "sugar"));
Stream에서 작업한 결과를 List로 반환받는다.
List<String> nameList = productList.stream()
.map(Product::getName)
.collect(Collectors.toList());
Stream에서 작업한 결과를 하나의 String으로 이어붙인다.
파라미터는 (구분자, 접두사, 접미사)
String listToString = productList.stream()
.map(Product::getName)
.collect(Collectors.joining("-", "@", "#"));
// @potatoes-orange-lemon-bread-sugar#
Collectors.averagingInt(), Collectors.summingInt(), Collectors.summarizingInt(), Collectors.groupingBy(), Collectors.partitioningBy()
names.stream()
.forEach(System.out::println);