programing

Java: Array List에서 중복을 검출하시겠습니까?

javaba 2022. 10. 7. 23:32
반응형

Java: Array List에서 중복을 검출하시겠습니까?

Java에서 Array List에 여러 개의 동일한 요소가 포함되어 있는지 여부를 검출(true/false 반환)하려면 어떻게 해야 합니까?

고마워요, 테리

편집 깜빡 잊고 "블록"을 서로 비교하는 것이 아니라 해당 정수 값을 비교합니다.각 "블록"에는 int가 있으며 이것이 그들을 다르게 만드는 것입니다.getNum이라는 이름의 메서드를 호출하여 특정 블록의 int를 찾습니다(예: table1[0][2.getNum();

가장 간단한 방법: 전체 컬렉션을 Set(Collection) 컨스트럭터 또는 Set.addAll을 사용하여 세트에 덤프한 다음 Set의 크기가 ArrayList와 동일한지 확인합니다.

List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);

if(set.size() < list.size()){
    /* There are duplicates */
}

업데이트: 질문을 올바르게 이해한 경우 블록의 2D 배열을 사용할 수 있습니다.

블록 테이블[][];

중복된 행이 있는지 탐지하고 싶으시다고요?

이 경우 블록이 "equals"와 "hashCode"를 올바르게 구현한다고 가정하면 다음과 같이 할 수 있습니다.

for (Block[] row : table) {
   Set set = new HashSet<Block>(); 
   for (Block cell : row) {
      set.add(cell);
   }
   if (set.size() < 6) { //has duplicate
   }
}

구문에 대해서는 100% 확신할 수 없기 때문에 다음과 같이 쓰는 것이 안전할 수 있습니다.

for (int i = 0; i < 6; i++) {
   Set set = new HashSet<Block>(); 
   for (int j = 0; j < 6; j++)
    set.add(table[i][j]);
 ...

Set.add이 이미 있는 "false"를 반환하는 및 할 수 .구제금융을 받다false중복되는 것이 있는지 여부만 알면 됩니다.

「」, 「」의 해 코드가되었습니다.Set#add★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

public static <T> boolean hasDuplicate(Iterable<T> all) {
    Set<T> set = new HashSet<T>();
    // Set#add returns false if the set does not change, which
    // indicates that a duplicate element has been added.
    for (T each: all) if (!set.add(each)) return true;
    return false;
}

Java 8+에서는 Stream API를 사용할 수 있습니다.

boolean areAllDistinct(List<Block> blocksList) {
    return blocksList.stream().map(Block::getNum).distinct().count() == blockList.size();
}

중복을 전혀 방지하려면 중복을 탐지하는 중간 프로세스를 제거하고 세트를 사용해야 합니다.

중복된 요소를 반환하기 위한 코드 개선

  • 컬렉션에서 중복 항목을 찾을 수 있습니다.
  • 사본 세트를 반환하다
  • 고유 요소는 세트에서 얻을 수 있습니다.

public static <T> List getDuplicate(Collection<T> list) {

    final List<T> duplicatedObjects = new ArrayList<T>();
    Set<T> set = new HashSet<T>() {
    @Override
    public boolean add(T e) {
        if (contains(e)) {
            duplicatedObjects.add(e);
        }
        return super.add(e);
    }
    };
   for (T t : list) {
        set.add(t);
    }
    return duplicatedObjects;
}


public static <T> boolean hasDuplicate(Collection<T> list) {
    if (getDuplicate(list).isEmpty())
        return false;
    return true;
}

비슷한 수술을 해야 했어요Stream가 없었어요내가 생각해낸 건 이거야

public static <T> boolean areUnique(final Stream<T> stream) {
    final Set<T> seen = new HashSet<>();
    return stream.allMatch(seen::add);
}

이것은 되었을 때 수 있는 모든 을 에 넣는 .Set이치노 이 다음과

List<T> list = ...
boolean allDistinct = areUnique(list.stream());

어떤 식으로든 Comparable 요소(순서가 진정한 의미를 갖는다는 사실은 무관합니다.순서는 평등에 대한 정의와 일치하기만 하면 됩니다)의 가장 빠른 중복 제거 솔루션은 목록을 정렬합니다(0(n log(n)). 그런 다음 단일 패스를 수행하여 동일한 요소(즉, 각 O에 이어지는 동일한 요소)를 찾습니다.(이것은 O(n)입니다).

전체 복잡도는 O(n log(n)가 됩니다.O(n log(n)는 세트(n)의 길이)와 거의 동일하지만 상수는 훨씬 작습니다.이는 정렬/중복 제거의 상수가 요소 비교 비용에서 비롯되는 반면 집합에서 발생하는 비용은 해시 계산과 하나(아마도 여러 개)의 해시 비교에서 비롯될 가능성이 높기 때문입니다.해시 베이스의 Set 실장을 사용하고 있는 경우, 즉 Tree 베이스에서는 O(n log²(n)가 취득되기 때문에, 한층 더 나빠집니다.

다만, 중복을 제거할 필요는 없고, 존재 여부만 테스트하는 것으로 알고 있습니다.따라서 어레이에서 머지 또는 힙 정렬 알고리즘을 수동으로 코드화해야 합니다.이 알고리즘은 비교기가 0을 반환하고 다른 방법으로 정렬을 완료하면 단순히 true를 반환하는 것(즉, "dup"이 있습니다)을 종료하고 정렬된 어레이의 반복 테스트를 통과합니다.실제로 병합 또는 힙 정렬에서는 정렬이 완료되었을 때 두 요소가 이미 최종 위치에 있지 않는 한 중복된 모든 쌍을 비교합니다(그럴 가능성은 낮습니다).따라서 조정된 정렬 알고리즘은 성능을 크게 향상시킵니다(그것을 증명해야 하지만 조정된 알고리즘은 균일하게 랜덤한 데이터의 O(log(n)에 있어야 합니다).

중복된 값 세트를 원하는 경우:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FindDuplicateInArrayList {

    public static void main(String[] args) {

        Set<String> uniqueSet = new HashSet<String>();
        List<String> dupesList = new ArrayList<String>();
        for (String a : args) {
            if (uniqueSet.contains(a))
                dupesList.add(a);
            else
                uniqueSet.add(a);
        }
        System.out.println(uniqueSet.size() + " distinct words: " + uniqueSet);
        System.out.println(dupesList.size() + " dupesList words: " + dupesList);
    }
}

또한 경우에 따라 값을 트리밍하거나 소문자를 사용할 수도 있습니다.

간단히 말하면 1) 모든 항목이 동일한지 확인 2) 어레이를 정렬하고 2) 어레이를 반복하여 중복되는 항목을 찾습니다.

목록의 중복을 확인하려면 다음 코드를 사용합니다.중복된 것이 들어 있는 세트를 드립니다.

 public Set<?> findDuplicatesInList(List<?> beanList) {
    System.out.println("findDuplicatesInList::"+beanList);
    Set<Object> duplicateRowSet=null;
    duplicateRowSet=new LinkedHashSet<Object>();
            for(int i=0;i<beanList.size();i++){
                Object superString=beanList.get(i);
                System.out.println("findDuplicatesInList::superString::"+superString);
                for(int j=0;j<beanList.size();j++){
                    if(i!=j){
                         Object subString=beanList.get(j);
                         System.out.println("findDuplicatesInList::subString::"+subString);
                         if(superString.equals(subString)){
                             duplicateRowSet.add(beanList.get(j));
                         }
                    }
                }
            }
            System.out.println("findDuplicatesInList::duplicationSet::"+duplicateRowSet);
        return duplicateRowSet;
  }

문제를 해결하는 최선의 방법은 HashSet을 사용하는 것입니다.

ArrayList<String> listGroupCode = new ArrayList<>();
listGroupCode.add("A");
listGroupCode.add("A");
listGroupCode.add("B");
listGroupCode.add("C");
HashSet<String> set = new HashSet<>(listGroupCode);
ArrayList<String> result = new ArrayList<>(set);

결과 어레이 리스트를 인쇄하기만 하면 중복되지 않고 결과를 확인할 수 있습니다.

이 답변은 Kotlin으로 작성되어 있지만 Java로 쉽게 번역할 수 있습니다.

어레이 리스트의 사이즈가 일정한 작은 범위내에 있는 경우는, 이 솔루션이 최적입니다.

var duplicateDetected = false
    if(arrList.size > 1){
        for(i in 0 until arrList.size){
            for(j in 0 until arrList.size){
                if(i != j && arrList.get(i) == arrList.get(j)){
                    duplicateDetected = true
                }
            }
        }
    }
private boolean isDuplicate() {
    for (int i = 0; i < arrayList.size(); i++) {
        for (int j = i + 1; j < arrayList.size(); j++) {
            if (arrayList.get(i).getName().trim().equalsIgnoreCase(arrayList.get(j).getName().trim())) {
                return true;
            }
        }
    }

    return false;
}
    String tempVal = null;
    for (int i = 0; i < l.size(); i++) {
        tempVal = l.get(i); //take the ith object out of list
        while (l.contains(tempVal)) {
            l.remove(tempVal); //remove all matching entries
        }
        l.add(tempVal); //at last add one entry
    }

주의: 이 경우 목록의 선두에서 항목이 삭제되므로 성능에 큰 영향을 미칩니다.이를 해결하기 위해 두 가지 옵션이 있습니다.1) 역순으로 반복하여 요소를 제거한다.2) Array List 대신 Linked List를 사용합니다.다른 컬렉션을 사용하지 않고 목록에서 중복을 삭제하기 위해 면접에서 질문하는 편향된 질문으로 인해 위의 예가 답변입니다.하지만 현실에서는 이것을 달성해야 한다면 리스트에서 세트까지 요소를 심플하게 넣을 것이다!

/**
     * Method to detect presence of duplicates in a generic list. 
     * Depends on the equals method of the concrete type. make sure to override it as required.
     */
    public static <T> boolean hasDuplicates(List<T> list){
        int count = list.size();
        T t1,t2;

        for(int i=0;i<count;i++){
            t1 = list.get(i);
            for(int j=i+1;j<count;j++){
                t2 = list.get(j);
                if(t2.equals(t1)){
                    return true;
                }
            }
        }
        return false;
    }

「」를 한 예.equals():

public class Reminder{
    private long id;
    private int hour;
    private int minute;

    public Reminder(long id, int hour, int minute){
        this.id = id;
        this.hour = hour;
        this.minute = minute;
    }

    @Override
    public boolean equals(Object other){
        if(other == null) return false;
        if(this.getClass() != other.getClass()) return false;
        Reminder otherReminder = (Reminder) other;
        if(this.hour != otherReminder.hour) return false;
        if(this.minute != otherReminder.minute) return false;

        return true;
    }
}
    ArrayList<String> withDuplicates = new ArrayList<>();
    withDuplicates.add("1");
    withDuplicates.add("2");
    withDuplicates.add("1");
    withDuplicates.add("3");
    HashSet<String> set = new HashSet<>(withDuplicates);
    ArrayList<String> withoutDupicates = new ArrayList<>(set);

    ArrayList<String> duplicates = new ArrayList<String>();

    Iterator<String> dupIter = withDuplicates.iterator();
    while(dupIter.hasNext())
    {
    String dupWord = dupIter.next();
    if(withDuplicates.contains(dupWord))
    {
        duplicates.add(dupWord);
    }else{
        withoutDupicates.add(dupWord);
    }
    }
  System.out.println(duplicates);
  System.out.println(withoutDupicates);

언급URL : https://stackoverflow.com/questions/562894/java-detect-duplicates-in-arraylist

반응형