List 중복제거
List는 기본적으로 중복을 허용합니다. 하지만 때때로 필요에 따라 List의 중복을 제거해야 할 때가 있습니다.
오늘은 List의 중복을 제거하는 방법에 대해 알아보겠습니다.

public class ListDistinct { public static void main(String[] args) { List<String> before = new ArrayList<>(); before.add("1"); before.add("1"); before.add("2"); before.add("3"); before.add("3"); before.add("4"); before.add("7"); before.add("6"); before.add("6"); before.add("5"); before.add("5"); before.add("5"); List<String> byLogic = getDistinctByLogic(before); System.out.println("byLogic : " + byLogic); System.out.println("-----------------"); List<String> byHashSet = getDistinctByHashSet(before); System.out.println("byHashSet : " +byHashSet); System.out.println("-----------------"); List<String> byTreeSet = getDistinctByTreeSet(before); System.out.println("byTreeSet : " + byTreeSet); System.out.println("-----------------"); List<String> byStream = getDistinctByStream(before); System.out.println("byStream : " + byStream); } public static List<String> getDistinctByLogic(List<String> list) { List<String> result = new ArrayList<>(); for (String str : list) { if (!result.contains(str)) result.add(str); } return result; } public static List<String> getDistinctByHashSet(List<String> list) { HashSet<String> tmp = new HashSet<>(list); List<String> result = new ArrayList<>(tmp); return result; } public static List<String> getDistinctByTreeSet(List<String> list) { TreeSet<String> tmp = new TreeSet<>(list); List<String> result = new ArrayList<>(tmp); return result; } public static List<String> getDistinctByStream(List<String> list) { List<String> result = new ArrayList<>(); //result = list.stream().distinct().collect(Collectors.toList()); result = list.parallelStream().distinct().collect(Collectors.toList()); return result; } }
결과

byLogic : [1, 2, 3, 4, 7, 6, 5] ----------------- byHashSet : [1, 2, 3, 4, 5, 6, 7] ----------------- byTreeSet : [1, 2, 3, 4, 5, 6, 7] ----------------- byStream : [1, 2, 3, 4, 7, 6, 5]
반복문과 stream을 이용한 방법은 정렬이 되지 않고 HashSet, TreeSet을 이용한 방법은 정렬되는 것을 볼 수 있습니다.
List => Set으로 들어갈 때 정렬된 채로 들어가는걸로 보입니다. 자세한 건 좀 더 연구해봐야겠습니다.
성능은 반복문 > HashSet > TreeSet > Stream 순이라고 합니다. (실험 사이트)
반응형
'Java' 카테고리의 다른 글
[Java] 람다 (0) | 2020.07.12 |
---|---|
[Java] String.split(".") (0) | 2020.07.11 |
[Java]Immutable Object(불변객체) (0) | 2020.07.03 |
[Java] String = ""; vs new String(""); (0) | 2020.07.01 |
[Java] 배열을 ArrayList로 변환 (0) | 2020.06.30 |