Stream
Java 8 부터 도입된 Stream을 이용해서 중복 값을 찾는 방법을 알아보자.
방법
✔️1. Stream.distinct()
disticnt() 메서드는 중복되는 요소들을 제거하고 새로운 스트림을 반환한다.
📌 중복된 값을 제거하고 List 반환하기
List<String> list = Arrays.asList("A", "B", "B", "C", "D", "D");
List<String> distinctList = list.stream()
.distinct()
.collect(Collectors.toList());
// 결과
// [A, B, C, D]
📌 중복된 값이 무엇인지 찾기
List<String> list = new ArrayList(
Arrays.asList("A", "B", "B", "C", "D", "D")
);
List<String> distinctList = list.stream()
.distinct()
.collect(Collectors.toList());
for (String el : distinctList) {
li.remove(el);
}
// list에 담긴 값 : [B, D]
✔️2. Collectors.toSet() 이용하기
List 컬렉션과 달리 Set은 중복을 허용하지 않는다. (참고로 null은 허용하고, 저장순서 보장X)
Set의 add() 메소드를 이용해서 쉽게 중복 요소를 찾을 수 있다.
📌 Set.add()
add() 메소드는 인자로 전달된 요소를 저장하고, set에 존재하지 않는다면 true, 이미 존재한다면 false를 리턴한다.
public boolean add(E e)
📌 사용한 예제
Stream<String> stream = Stream.of("A", "B", "B", "C", "D", "D");
Set<String> set = new HashSet<>();
stream.filter(n -> !set.add(n))
.collect(Collectors.toSet())
.forEach(item -> System.out.println(item));
// 결과
B
D
✔️3. Collectors.toMap() 이용하기
stream 요소를 Map 컬렉션으로 변환한다.
📌 Function.identity() 는 현재 인자로 들어온 값을 그대로 반환하는 메소드다.
Stream<String> stream = Stream.of("A", "B", "B", "C", "D", "D");
Map<String, Integer> map = stream.collect(
Collectors.toMap(Function.identity(), value -> 1, Integer::sum)
);
// {A=1, B=2, C=1, D=2}
✔️4. Collections.frequency() 메서드
Collections.frequency() 메서드는 각 요소를 순회하여 요소의 개수를 반환한다.
📌 filter() 와 frequency() 이용하여 중복 요소 출력하기
List<String> list = Arrays.asList("A", "B", "B", "C", "D", "D");
list.stream()
.filter(i -> Collections.frequency(li, i) > 1)
.collect(Collectors.toSet())
.forEach(System.out::println);
'Back > Java' 카테고리의 다른 글
[JAVA] 파일 관련 Stream, I/O 성능 개선 (File 복사 기능) (2) | 2024.07.24 |
---|---|
[JAVA] Stream Collectors.groupingBy 널(null) 사용하기 (0) | 2023.04.07 |
[Java] Optional 개념, 사용법 (1) | 2023.02.21 |
[JAVA] Reflection 이용해서 필드값 set 하기 (0) | 2022.04.11 |
[JAVA] 데이터 직렬화(serialization) 하는 이유 (0) | 2022.02.11 |
댓글