배열이나 컬렉션에 담긴 데이터를 다룰 때, 반복문이나, iterator를 사용하면 코드가 길어지고, 가독성이 떨어진다. 이 문제를 해결하기위해 Stream API 등장.
filter, distinctmap, flatMaplimit, skipsortedforEachfindFirst, findAnycount, min, maxsum, averagecollectList<String> elements = Stream.of("a", "b", "c")
.filter(element -> element.contains("b"))
.collect(Collectors.toList());
Optional<String> anyElement = elements.stream().findAny();
System.out.println(anyElement.orElse("암것두 없어"));
Optional<String> firstElement = elements.stream().findFirst();
System.out.println(firstElement.orElse("한개두 없어"));Stream<String> onceModifiedStream = Stream.of("abcd", "bbcd", "cbcd");
Stream<String> twiceModifiedStream = onceModifiedStream
.skip(1)
.map(element -> element.substring(0, 3));
System.out.println(twiceModifiedStream); //?
System.out.println(twiceModifiedStream.collect(Collectors.toList()));class Product {
private int age;
private String name;
public Product(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}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")
);
List<String> collectorCollection = productList.stream()
.map(Product::getName)
.collect(Collectors.toList());
System.out.println(collectorCollection);
double averageAge = productList.stream()
.collect(Collectors.averagingInt(Product::getAge));
System.out.println("나이 평균 : " + averageAge);
int summingAge = productList.stream().mapToInt(Product::getAge).sum();
System.out.println("나이 총합 : " + summingAge);