[java] ArrayList에서 반복되는 요소를 어떻게 제거합니까?

가 있고 ArrayList<String>반복되는 문자열을 제거하고 싶습니다. 어떻게해야합니까?



답변

에서 중복을 원하지 않으면 중복 을 허용하는를 Collection사용하는 이유를 고려해야합니다 Collection. 반복되는 요소를 제거하는 가장 쉬운 방법은 내용을 Set(중복을 허용하지 않음)에 추가 한 다음에 Set다시 추가하는 것입니다 ArrayList.

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

물론 이것은의 요소 순서를 파괴합니다 ArrayList.


답변

변환하더라도 ArrayListA를가 HashSet효과적으로 중복 제거 당신이 삽입 순서를 유지해야하는 경우, 차라리이 변형을 사용하는 것이 좋을 것

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

그런 다음 List참조를 다시 가져와야하는 경우 변환 생성자를 다시 사용할 수 있습니다.


답변

자바 8 :

List<String> deduped = list.stream().distinct().collect(Collectors.toList());

있습니다 해시 코드가-동일 리스트 회원을위한 계약은 제대로 작동하려면 필터링 존중해야한다.


답변

다음과 String같은 목록이 있다고 가정하십시오 .

List<String> strList = new ArrayList<>(5);
// insert up to five items to list.        

그런 다음 여러 가지 방법으로 중복 요소를 제거 할 수 있습니다.

Java 8 이전

List<String> deDupStringList = new ArrayList<>(new HashSet<>(strList));

참고 : 게재 신청서를 유지하려면 다음 LinkedHashSet대신에 사용해야합니다 .HashSet

구아바 사용하기

List<String> deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));

Java 8 사용

List<String> deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());

참고 : 특정 목록 구현 에서 결과를 수집하려는 경우 예 LinkedList를 들어 위의 예를 다음과 같이 수정할 수 있습니다.

List<String> deDupStringList3 = strList.stream().distinct()
                 .collect(Collectors.toCollection(LinkedList::new));

parallelStream위의 코드에서도 사용할 수 있지만 예상되는 성능상의 이점을 제공하지 않을 수 있습니다. 자세한 내용은 이 질문 을 확인하십시오 .


답변

중복을 원하지 않으면 a 대신 Set을 사용 하십시오List . 를 a List로 변환하려면 Set다음 코드를 사용할 수 있습니다.

// list is some List of Strings
Set<String> s = new HashSet<String>(list);

당신은 변환 동일한 구성을 사용할 수 있습니다 정말 필요한 경우 Set에 다시 List.


답변

이 방법으로도 할 수 있으며 순서를 유지하십시오.

// delete duplicates (if any) from 'myArrayList'
myArrayList = new ArrayList<String>(new LinkedHashSet<String>(myArrayList));


답변

Java 8 스트림은 목록에서 중복 요소를 제거하는 매우 간단한 방법을 제공합니다. 고유 한 방법을 사용합니다. 도시 목록이 있고 해당 목록에서 중복을 제거하려면 한 줄로 할 수 있습니다.

 List<String> cityList = new ArrayList<>();
 cityList.add("Delhi");
 cityList.add("Mumbai");
 cityList.add("Bangalore");
 cityList.add("Chennai");
 cityList.add("Kolkata");
 cityList.add("Mumbai");

 cityList = cityList.stream().distinct().collect(Collectors.toList());

arraylist에서 중복 요소를 제거하는 방법