


public class BasicStream2 {
public static void main(String[] args) {
List<DishVO> dishes = new ArrayList<DishVO>();
dishes.add(new DishVO("Pork", 1000, "MEET"));
dishes.add(new DishVO("Salmon", 500, "FISH"));
dishes.add(new DishVO("Beef", 1200, "MEET"));
dishes.add(new DishVO("Chicken",900, "MEET"));
dishes.add(new DishVO("Pizza", 1500, "OTHER"));
dishes.add(new DishVO("Rice", 300, "OTHER"));
dishes.add(new DishVO("French Fries", 700, "OTHER"));
dishes.stream()
.filter((dish)-> dish.isVegeterian())
.forEach((dish)->{
System.out.println(dish.getName());
});
dishes.stream()
.filter(DishVO::isVegeterian)
.map(DishVO::getName)
.forEach(System.out::println);
List<String> meetDishName= dishes.stream()
.filter((dish)->dish.getCategory().equals("MEET"))
.map(DishVO::getName)
.collect(Collectors.toList());
System.out.println(meetDishName);
Integer[] numberArray= {1,2,1,3,3,2,4};
List<Integer> numberList = Arrays.asList(numberArray);
List<Integer> evenList= numberList.stream()
.filter((number)-> number%2==0)
.distinct()
.collect(Collectors.toList());
System.out.println(evenList);
findAny
Optional<DishVO> anyDish= dishes.parallelStream()
.filter((dish)->dish.getCalories()<1200)
.findAny();
DishVO one=anyDish.get();
System.out.println(one.getName()+"\n"+
one.getCalories());
Optional<DishVO> anyLowCaloryDish=
dishes.parallelStream()
.filter((dish)->dish.getCalories()<100)
.findAny();
DishVO lowCaloryDish=anyLowCaloryDish
.orElse(new DishVO("SimpleFood", 10, "OTHER"));
System.out.println(lowCaloryDish.getName()+"\n"+
lowCaloryDish.getCalories());
anyLowCaloryDish=
dishes.parallelStream()
.filter((dish)->dish.getCalories()<500)
.findAny();
lowCaloryDish=anyLowCaloryDish
.orElse(new DishVO("SimpleFood", 10, "OTHER"));
System.out.println(lowCaloryDish.getName()+"\n"+
lowCaloryDish.getCalories());
정리
- stream : 내부 반복자
- parallelStream : 병렬처리를 하는 내부 반복자(데이터의 수가 매우 많을때 사용)
- filter : stream내의 데이터를 정제하는 것(파라미터 ->boolean 반환)- Predicate
- map : steam내의 데이터 형태를 변경하는 것(파라미터 -> 변경된 값 반환) -Function
- flatMap(활용도 낮음) 함수 내에서 만들어진 다른형태의 stream을 원본 스트림으로 변환- Function
- distinct : stream 내부 데이터 중 중복된 값만 제거
- sort: 정렬
- count : stream 내부의 요소 개수를 세어주는 최종함수
- forEach : stream 내부의 값을 반복해주는 최종함수.
- collect : stream 내부의 값을 List,Map,Set,Grouping을 해주는 최종함수.
- findAny : stream 내부의 값 중 아무거나 하나를 반환시키는 최종 함수(Optional)
- findFirst : stream 내부의 값 중 가장 첫 번째 요소를 반환시키는 최종 함수(Optional)
- peak : stream 내부의 값을 임시로 출력하고자 할 때 사용되는 함수(forEach와 동일)
- limit : stream 내부의 값을 원하는 개수 만큼 선착순으로 가져오는 함수
- skip : stream 내부의 값 중 앞에서 부터 원하는 개수만큼 건너띄는 함수.