-
Java - List 중복 제거Java 2022. 8. 1. 18:53반응형
TL;DR
Stream.distinct()를 통해서 중복 제거를 할 수 있다.
자바 List에서 중복 제거 방법
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; class Example { public static void main(String[] args) { List<String> list = Arrays.asList("A", "A", "B", "C", "C", "D"); List<String> result = list.stream().distinct().collect(Collectors.toList()); System.out.println("result: " + result); } }
list.stream().disctinct()로 중복을 제거하고 .collect(Collectors.toList())를 통해서 list 출력할 수 있다.
중복된 A, C가 제거되서 A, B, C, D 가 출력된다.
결과
result: [A, B, C, D]
List의 중복 제외 리스트 사이즈 구하기
import java.util.Arrays; import java.util.List; class Example { public static void main(String[] args) { List<String> list = Arrays.asList("A", "A", "B", "C", "C", "D"); System.out.println("count: " + list.stream().distinct().count()); } }
중복 제거한 리스트의 count를 구할 수 있다.
결과
count: 4
관련글
반응형'Java' 카테고리의 다른 글
Java - List(Collection) Iterable로 변환 (0) 2022.09.05 Java - generic 이해하기 (0) 2022.08.12 Java - List의 Null 체크하는 방법 (CollectionUtils) (0) 2022.07.27 Java - String을 Long으로 변환하기 (0) 2022.07.25 Java - Int를 Long으로 변환, Long을 Int로 변환 (0) 2022.07.18