Java Stream API와 람다 표현식 활용 가이드

중복 제거

  • 두 개의 리스트 객체 조건에 따른 중복 제거
List<Member> memberList와 List<Employee> employeeList

// memberList의 Member id가 employeeList의 Employee id와 일치하지 않는 객체 제거
List<Member> filteredList = memberList.stream()
    .filter(member -> !employeeList.stream().map(emp -> emp.getEmployeeId()).collect(Collectors.toList())
    .contains(member.getMemberId()))
    .collect(Collectors.toList());

  • 중복 제거
 // 단일 조건 중복 제거   
list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
                -> new TreeSet<>(Comparator.comparing(member -> member .getMemberId()))), ArrayList::new));  

// 다중 조건 확장
list.stream().collect(Collectors.collectingAndThen(
        Collectors.toCollection(() -> new TreeSet<>(
                Comparator.comparing(member -> member.getAge() + ";" + member.getFullName()))), ArrayList::new))                

  • 간단한 리스트 집합 교집합, 중복 제거, 차집합 연산
// 교집합 (parallelStream()은 병렬 스트림 순회, 다중 스레드; stream()은 순차 스트림)
List<String> intersection = list1.stream()
    .filter(item -> list2.contains(item))
    .collect(toList());

// 차집합 (list1 - list2)
List<String> difference1 = list1.stream()
    .filter(item -> !list2.contains(item))
    .collect(toList());

// 차집합 (list2 - list1)
List<String> difference2 = list2.stream()
    .filter(item -> !list1.contains(item))
    .collect(toList());

// 중복 제거
List<String> allDistinct = listAll.stream()
    .distinct()
    .collect(toList());

정렬

List<Student> sortedList = list.stream()
    .sorted((s1,s2) -> s1.getAge() - s2.getAge())
    .collect(Collectors.toList());
    
List<Student> sortedList =  list.stream()
.sorted(Comparator.comparing(StudentRecord::getPriority))
.collect(Collectors.toList());    

List<Student> sortedList =  list.stream()
.sorted(Comparator.comparing(StudentRecord::getPriority).reversed())
.collect(Collectors.toList()); 

// 다중 조건 조합 정렬
// 먼저 msg(오름차순), 그 다음 id(오름차순)
list.stream()
    .sorted(Comparator.comparing(StudentMessage::getMessage)
    .thenComparing(StudentMessage::getStudentId))
    .collect(Collectors.toList()); 

// msg(오름차순), 그 다음 id(내림차순)
list.stream()
    .sorted(Comparator.comparing(StudentMessage::getMessage)
    .thenComparing(Comparator.comparing(StudentMessage::getStudentId).reversed()))
    .collect(Collectors.toList()); 

// 먼저 msg(내림차순), 그 다음 id(내림차순)
list.stream()
    .sorted(Comparator.comparing(StudentMessage::getMessage)
    .thenComparing(StudentMessage::getStudentId).reversed())
    .collect(Collectors.toList()); 
    
// 먼저 msg(내림차순), 그 다음 id(오름차순)
list.stream()
    .sorted(Comparator.comparing(StudentMessage::getMessage).reversed()
    .thenComparing(StudentMessage::getStudentId))
    .collect(Collectors.toList()); 

필터링

List<Student> filteredList = list.stream()
    .filter(item -> item.getAge() > 3)
    .collect(Collectors.toList());

선택 및 변환

List<String> nameList1 = list.stream()
    .map(Student::getFullName)
    .collect(Collectors.toList());
    
List<String> nameList2 = list.stream()
    .map(item -> item.getFullName())
    .collect(Collectors.toList());
    
// 필터링과 선택 결합
List<String> teacherIds = pList.stream()
    .filter(s -> s.getId().equals("333"))
    .map(p -> p.getUserId())
    .collect(Collectors.toList());
    
// .collect(Collectors.toMap(LogData::getRequestDate, LogData::getRequestDateNum)) 

통계

// 평균 계산 sum() .mapToDouble()을 double로 변환. 다른 유형 변환도 가능. max(), min(), average() 등도 있음.

double sum = list.stream().mapToDouble(Student::getAge).sum();

Optional<StudentMessage> maxMessage = list.stream()
    .collect(Collectors.maxBy(Comparator.comparing(StudentMessage::getStudentId)));
Long maxId = maxMessage.get().getStudentId();

LongSummaryStatistics stats = list.stream()
    .collect(Collectors.summarizingLong(StudentMessage::getStudentId));

//  합계 계산 stats.getSum()
//  최대값 계산 stats.getMax()
// 최소값 계산 stats.getMin()
// 평균값 계산 stats.getAverage()

그룹화

Map<Integer, List<Student>> groupMap = list.stream()
    .collect(Collectors.groupingBy(Student::getAge));
    
// 다중 그룹화
Map<String, Map<Integer, List<Student>>> multiGroupMap = list.stream()
    .collect(Collectors.groupingBy(t->t.getFullName(),Collectors.groupingBy(t->t.getAge())));
    
// 그룹화 및 집계 계산        Collectors.summarizingLong()
Map<String, Map<Integer, LongSummaryStatistics>> statsGroupMap = list.stream()
    .collect(Collectors.groupingBy(t->t.getFullName(),Collectors.groupingBy(t->t.getAge(),Collectors.summarizingLong(Student::getSize))));

반복

items.forEach(item->{
    System.out.println(item);
});

태그: java stream-api lambda Java8

7월 23일 01:21에 게시됨