kok202
자바 8 Stream

2019. 6. 6. 21:47[개발] 기록

이해를 돕기위해 가능하면 람다식은 풀어서 씁니다.

@Data
@AllArgsContstructor
public class Unit {
    private String races;
    private String name;
    private int mineral;
    private int gas;
}
List<Unit> units = Arrays.asList(
    new Unit("protoss", "zealot", 100, 0),
    new Unit("protoss", "dragoon", 125, 50),
    new Unit("protoss", "high templar", 50, 150),
    new Unit("terran", "marine", 50, 0),
    new Unit("terran", "medic", 50, 25),
    new Unit("terran", "firebat", 50, 25),
    new Unit("zerg", "zergling", 50, 0),
    new Unit("zerg", "hydralisk", 75, 25),
    new Unit("zerg", "mutalisk", 100, 100)
); 

직렬 처리 : stream() 

병렬 처리 : parallelStream() 

 

 

 

 

 

순회

units.stream()
     .foreach(member -> {
         System.out.println(member.toString());
     });

 

 

 

 

 

모든 유닛의 미네랄 평균

units.stream()
     .mapToInt(unit -> { return unit.getMineral(); })
     .average()
     .getAsDouble();

min()

max()

sum()

count()

average()

reduce()

 

mapToInt() : 스트림을 순회하는 element 에서 Int 인 값을 추출해서 앞으로의 stream 체인에서는 이를 element로 사용하겠다.

flatMap() : 스트림을 순회하는 element 에서 유의미한 데이터만 추출해서 새로운 Collector 로 바꾸고 앞으로의 stream 체인에서는 이를 element로 사용하겠다.

 

 

 

 

프로토스 유닛의 미네랄 평균

units.stream()
     .filter(unit -> { return unit.getRaces().equals("protoss"); })
     .mapToInt(unit -> { return unit.getMineral(); })
     .average()
     .getAsDouble();

distinct()

filter()

 

 

 

 

 

테란 유닛 중에 팩토리 유닛이 있는가

boolean result = units.stream()
                      .filter(unit -> { return unit.getRaces().equals("terran"); })
                      .anyMatch(terranUnit -> {
                          terranUnit.getName().equals("sigetank") ||
                          terranUnit.getName().equals("vulture") ||
                          terranUnit.getName().equals("goliath")
                      });

allMatch()
anyMatch()

noneMatch()

 

 

 

 

 

저그 유닛 리스트만 얻기

List<Unit> zergUnits = units.stream()
                            .filter(unit -> { return unit.getRaces().equals("zerg"); })
                            .collect(
                                Collectors.toList()
                            );

 

 

 

 

 

맵 (종족, 유닛 리스트) 얻기

Map<String, List<Unit>> racesMap = units.stream()
                                        .collect(
                                            Collectors.groupingBy(
                                                unit -> { return unit.getRaces(); },
                                                Collectors.toList()
                                            )
                                        );

Collectors.toList() 가 없어도 된다.

Map<String, List<Unit>> racesMap = units.stream()
                                        .collect(
                                            Collectors.groupingBy(
                                                unit -> { return unit.getRaces(); }
                                            )
                                        );

람다식 축약 + 한줄로 정리하자

Map<String, List<Unit>> racesMap = units.stream().collect(Collectors.groupingBy(Unit::getRaces()));

 

 

 

 

 

 

'[개발] 기록' 카테고리의 다른 글

Already had POJO for id 에러  (0) 2019.08.05
mvn vs mvnw  (0) 2019.06.26
자바의 병렬 처리 발전사  (0) 2019.05.03
Java Optional class  (0) 2019.04.25
Reactive connection with DB  (0) 2019.04.18