기초/JAVA

[JAVA] Stream groupingBy

장동규 2022. 9. 12. 23:09

리스트를 그룹화 할 코드가 생겼다.

혹시나 java에서도 SQL처럼 group by를 할 수 있을까 하여 검색하다가 발견했다.

 

기존 Map을생성하고 반복문을 돌려 put하던 소스를 아래 소스와 같이 stream  / groupingBy로 작성할 수 있다.

 

공식 API 문서 : https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

 

Collectors (Java Platform SE 8 )

Returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map. The classification function maps elements to some key type K. The collector p

docs.oracle.com

 

 

List< T > list = new ArrayList<>();

Map< T, Long > counted = list
	.stream()
    .collect( Collectors.groupingBy(Function.identity(), Collectors.counting()));

 

 

Collection Max, Min 

Collections.min(numbers);
Collections.max(numbers);