사용하는 이유는 코드의 가독성을 좋게 하기 위해서이다.
// 일반 for문
for (String a : list) {
System.out.println(a);
}
// stream()의 foreach 메소드 활용
list.forEach(a -> System.out.println(a));
약 3줄로 쓸 코드를 한 줄로 줄인 것을 볼 수 있다!!!
collection.forEach(변수명 -> 반복처리(변수))
String[] strArray = { "w", "o", "r", "l", "d" };
Arrays.stream(strArray).forEach(s -> System.out.println(s));
Map<String, String> map = new HashMap<>();
map.put("bright", "dark");
map.put("sun", "moon");
map.forEach((key, value) -> System.out.println(key + " : " + value);
// 출력 결과
// bright : dark
// sun : moon
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.forEach(s -> System.out.println(list.indexOf(s) + " : " + s));
List<String> words = Arrays.asList("apple", "banana", "orange", "grape", "kiwi");
words.stream().forEach(System.out::println);
// 위의 System.out::println 코드는 (x) -> System.out.println(x)와 동일