반응형

Java8 Stream 활용 예

 

- List to Result

// 합계
integerList.stream().reduce(Integer::sum); // returnType Optional<Integer>
integerList.stream().reduce((a,b) -> a + b); // returnType Optional<Integer>
integerList.stream().reduce(0, Integer::sum); // returnType Integer
integerList.stream().reduce(0, (a,b) -> a + b); // returnType Integer

// 문자열 변환
stringList.stream().collect(Collectors.joining(",")); // {1,3,2,5,4} -> "1,3,2,5,4"

 

- Grouping

// 객체 내 특정 데이터를 기준으로, 또 다른 특정 데이터를 그룹핑
Map<String, List<Integer>> myVoIntegerMap =
	myVoList.stream().collect(Collectors.groupingBy(MyVo::getKeyString, Collectors.mapping(MyVo::getInteger, Collectors.toList())));

// 객체 내 특정 데이터를 기준으로, 객체 자체를 그룹핑
Map<String, List<MyVo>> myVoMap =
	myVoList.stream().collect(Collectors.groupingBy(MyVo::getKeyString));

// 두 개의 키를 기준으로 이중 Map 생성
Map<String, Map<String, MyVo>> myVoDoubleMap =
	myVoList.stream().collect(Collectors.groupingBy(MyVo::getId, Collectors.toMap(MyVo::getSubId, Function.identity())));

 

- Order By Item

// Normal (오름차순)
list.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());
list.stream().sorted().collect(Collectors.toList());
list.stream().sorted((a,b) -> a.compareTo(b)).collect(Collectors.toList());

// Normal Reverse (내림차순)
list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
list.stream().sorted((a,b) -> b.compareTo(a)).collect(Collectors.toList());

// Custom Object
list.stream().sorted(Comparator.comparing(MyVo::getItem)).collect(Collectors.toList());

// Custom Object Reverse
list.stream().sorted(Comparator.comparing(MyVo::getItem, Comparator.reverseOrder())).collect(Collectors.toList());

// Multiple Sort
 list.stream().sorted(Comparator.comparing(MyVo::getItem1).thenComparing(MyVo::getItem2)).collect(Collectors.toList()).forEach(System.out::println);
      

 

- List to Map

Map<Integer, MyVo> myVoMap 
	= myVoList.stream().collect(Collectors.toMap(MyVo::getIndex, Function.identity()));
    
// 중복 제거
Map<Integer, MyVo> myVoMap 
    = myVoList.stream().collect(Collectors.toMap(MyVo::getIndex, Function.identity(), (oldValue, newValue) -> oldValue));

+ Function.indextity()는 현재 인자로 들어온 Item을 그대로 반환

 

- Map to List

List<MyVo> myVoList 
	= myVoMap.entrySet().stream().map(vo->vo.getValue()).collect(Collectors.toList());

 

반응형

'Java' 카테고리의 다른 글

[SpringBoot] H2 연동  (0) 2020.07.21
[Spring] App 구동 후 자동 작업 실행  (0) 2020.02.23
리스트 순환 중 아이템 삭제  (0) 2019.12.08
[Spring] Cache 적용  (0) 2019.09.28
Spring Boot + MySQL 연동  (0) 2019.09.14

+ Recent posts