자바에서 스트림은 크게 두가지로 나뉘어지게 된다.
1. 입출력(File I/O, System I/O)에 사용하는 스트림
2. Collection을 통해 다량의 데이터를 처리할때 사용하는 스트림
이번에 알아볼 스트림은 Collection 을 통한 다량의 데이터 처리를 위한 스트림이다.
Stream API
를 사용하면 기존에 반복문, 조건문 등을 통해서 구현해야 했던 코드들이
더욱 간결하고 가시성이 높아지게 할 수 있다.List<String> list = Arrays.asList("Lee", "Park", "Kim"); // 기존 Iterator<String> it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
List<String> list = Arrays.asList("Lee", "Park", "Kim"); // Stream 활용 list.stream().forEach(name -> System.out.println(name));
List<String> list = Arrays.asList("Lee", "Kim", "Park", "Hong", "Choi", "Song");
Stream<String> stream = list.stream(); // Stream 생성
System.out.println(stream.count()); // Stream 사용
stream.forEach(System.out::println); // Exception 발생
Stream.Builder<String> builder = Stream.builder();
builder.accept("Kim");
builder.accept("Lee");
builder.accept("Song");
builder.accept("Park");
builder.accept("Lee");
Stream<String> stream = builder.build();
stream.forEach(System.out::println);
연산 | 연산 인수 |
---|---|
filter | Predicate<T> |
map | Function<T, R> |
limit | |
sorted | Comparator<T> |
distinct |
stream.filter( customer -> customer.getAge() > 30).forEach(System.out::println);
@Override
public int compareTo(Customer customer) {
if(this.age > customer.getAge()){
return 1;
}else if(this.age == customer.getAge()){
return 0;
}else {
return -1;
}
}
customers.stream().sorted(Comparator.comparing(Customer::getName)).forEach(System.out::println);
refer : youtube '나무소리' https://www.youtube.com/@namoosori