List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream(); // 병렬 처리 스트림
Stream<Integer> iteratedStream =
Stream.iterate(30, n -> n + 2).limit(5); // [30, 32, 34, 36, 38]
List<String> names = Arrays.asList("Eric", "Elena", "Java");
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
List<List<String>> list =
Arrays.asList(Arrays.asList("a"),
Arrays.asList("b")); // [[a], [b]]
List<String> flatList =
list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList()); // [a, b]
// if students
students.stream()
.flatMapToInt(student ->
IntStream.of(student.getKor(),
student.getEng(),
student.getMath()))
.average().ifPresent(avg ->
System.out.println(Math.round(avg * 10)/10.0));
// Stream<T> peek(Consumer<? super T> action);
int sum = IntStream.of(1, 3, 5, 7, 9)
.peek(System.out::println) // 1, 3, 5, 7, 9
.sum(); // sun = 25
public <T> Stream<T> collectionToStream(Collection<T> collection) {
return Optional
.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
List<String> nullList = null;
nullList.stream()
.filter(str -> str.contains("a"))
.map(String::length)
.forEach(System.out::println); // NPE!
collectionToStream(nullList)
.filter(str -> str.contains("a"))
.map(String::length)
.forEach(System.out::println); // []
Guava는 불변 리스트 생성을 위 팩토리 메서드나 빌더 클래스를 제공합니다.
import com.google.common.collect.ImmutableList;
List<String> fruits = ImmutableList.of("Apple", "Banana", "Cherry");
fruits.add("Lemon"); // UnsupportedOperationException