문제

나는있다 ArrayList<String>, 그리고 나는 그것에서 반복 된 줄을 제거하고 싶습니다. 어떻게 할 수 있습니까?

도움이 되었습니까?

해결책

당신이 a에서 복제를 원하지 않는다면 Collection, 당신은 왜 당신이 사용하는지 고려해야합니다 Collection 복제를 허용합니다. 반복 요소를 제거하는 가장 쉬운 방법은 내용을 Set (복제를 허용하지 않음) 다음 추가 Set 다시 ArrayList:

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

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

다른 팁

변환하지만 ArrayList a HashSet 효과적으로 복제를 제거하고 삽입 순서를 보존 해야하는 경우이 변형을 사용하는 것이 좋습니다.

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

그런 다음 다시 돌아와야한다면 a List 참조, 변환 생성기를 다시 사용할 수 있습니다.

Java 8 :

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

이에 유의하십시오 해시 코드 평등 필터링이 올바르게 작동하도록 목록 회원 계약을 존중해야합니다.

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

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

실제로 필요한 경우 동일한 구조를 사용하여 변환 할 수 있습니다. Set 다시 a List.

목록이 있다고 가정 해 봅시다 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 또한 위의 코드에서는 예상 된 공연 혜택을 제공하지 않을 수 있습니다. 이것을 확인하십시오 의문 이상.

이런 식으로 수행하고 질서를 보존 할 수 있습니다.

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

다음은 목록 순서에 영향을 미치지 않는 방법입니다.

ArrayList l1 = new ArrayList();
ArrayList l2 = new ArrayList();

Iterator iterator = l1.iterator();

while (iterator.hasNext()) {
    YourClass o = (YourClass) iterator.next();
    if(!l2.contains(o)) l2.add(o);
}

L1은 원래 목록이고 L2는 반복 된 항목이없는 목록입니다 (귀하의 클래스는 평등을지지하려는 것에 따라 동등한 메소드를 갖도록하십시오).

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에서 중복 요소를 제거하는 방법

도 있습니다 ImmutableSet ~에서 구아바 옵션으로 (여기 문서입니다) :

ImmutableSet.copyOf(list);

사용하지 않고 ArrayList에서 중복을 제거 할 수 있습니다. 해시 세트 또는 Arraylist 하나 더.

이 코드를 시도해보세요 ..

    ArrayList<String> lst = new ArrayList<String>();
    lst.add("ABC");
    lst.add("ABC");
    lst.add("ABCD");
    lst.add("ABCD");
    lst.add("ABCE");

    System.out.println("Duplicates List "+lst);

    Object[] st = lst.toArray();
      for (Object s : st) {
        if (lst.indexOf(s) != lst.lastIndexOf(s)) {
            lst.remove(lst.lastIndexOf(s));
         }
      }

    System.out.println("Distinct List "+lst);

출력입니다

Duplicates List [ABC, ABC, ABCD, ABCD, ABCE]
Distinct List [ABC, ABCD, ABCE]

이것은 문제를 해결할 수 있습니다.

private List<SomeClass> clearListFromDuplicateFirstName(List<SomeClass> list1) {

     Map<String, SomeClass> cleanMap = new LinkedHashMap<String, SomeClass>();
     for (int i = 0; i < list1.size(); i++) {
         cleanMap.put(list1.get(i).getFirstName(), list1.get(i));
     }
     List<SomeClass> list = new ArrayList<SomeClass>(cleanMap.values());
     return list;
}

아마 약간 과잉이지만, 나는 이런 종류의 고립 된 문제를 즐깁니다. :)

이 코드는 임시 세트 (고유성 점검 용)를 사용하지만 원래 목록 내부의 요소를 제거합니다. Arraylist 내부의 요소 제거는 엄청난 양의 배열 복사를 유도 할 수 있으므로 제거 (int) -method는 피합니다.

public static <T> void removeDuplicates(ArrayList<T> list) {
    int size = list.size();
    int out = 0;
    {
        final Set<T> encountered = new HashSet<T>();
        for (int in = 0; in < size; in++) {
            final T t = list.get(in);
            final boolean first = encountered.add(t);
            if (first) {
                list.set(out++, t);
            }
        }
    }
    while (out < size) {
        list.remove(--size);
    }
}

우리가 그 동안 링크드리스트를위한 버전이 있습니다 (훨씬 더 좋습니다!) :

public static <T> void removeDuplicates(LinkedList<T> list) {
    final Set<T> encountered = new HashSet<T>();
    for (Iterator<T> iter = list.iterator(); iter.hasNext(); ) {
        final T t = iter.next();
        final boolean first = encountered.add(t);
        if (!first) {
            iter.remove();
        }
    }
}

마커 인터페이스를 사용하여 목록에 대한 통합 솔루션을 제시하십시오.

public static <T> void removeDuplicates(List<T> list) {
    if (list instanceof RandomAccess) {
        // use first version here
    } else {
        // use other version here
    }
}

편집 : 제네릭 스터프가 여기에 실제로 가치를 더하지 않는 것 같습니다. :)

public static void main(String[] args){
    ArrayList<Object> al = new ArrayList<Object>();
    al.add("abc");
    al.add('a');
    al.add('b');
    al.add('a');
    al.add("abc");
    al.add(10.3);
    al.add('c');
    al.add(10);
    al.add("abc");
    al.add(10);
    System.out.println("Before Duplicate Remove:"+al);
    for(int i=0;i<al.size();i++){
        for(int j=i+1;j<al.size();j++){
            if(al.get(i).equals(al.get(j))){
                al.remove(j);
                j--;
            }
        }
    }
    System.out.println("After Removing duplicate:"+al);
}

타사 라이브러리를 기꺼이 사용하려는 경우 방법을 사용할 수 있습니다. distinct() 안에 일식 컬렉션 (이전 GS 컬렉션).

ListIterable<Integer> integers = FastList.newListWith(1, 3, 1, 2, 2, 1);
Assert.assertEquals(
    FastList.newListWith(1, 3, 2),
    integers.distinct());

사용의 장점 distinct() 세트로 변환 한 다음 목록으로 돌아가는 대신 distinct() 원래 목록의 순서를 보존하여 각 요소의 첫 번째 발생을 유지합니다. 세트와 목록을 모두 사용하여 구현됩니다.

MutableSet<T> seenSoFar = UnifiedSet.newSet();
int size = list.size();
for (int i = 0; i < size; i++)
{
    T item = list.get(i);
    if (seenSoFar.add(item))
    {
        targetCollection.add(item);
    }
}
return targetCollection;

원래 목록을 Eclipse 컬렉션 유형으로 변환 할 수없는 경우 Listadapter를 사용하여 동일한 API를 얻을 수 있습니다.

MutableList<Integer> distinct = ListAdapter.adapt(integers).distinct();

메모: 나는 이클립스 컬렉션을위한 커피터입니다.

이 세 줄의 코드는 ArrayList 또는 컬렉션에서 복제 된 요소를 제거 할 수 있습니다.

List<Entity> entities = repository.findByUserId(userId);

Set<Entity> s = new LinkedHashSet<Entity>(entities);
entities.clear();
entities.addAll(s);

ArrayList를 채우는 경우 각 요소의 조건을 사용하십시오. 예를 들어:

    ArrayList< Integer > al = new ArrayList< Integer >(); 

    // fill 1 
    for ( int i = 0; i <= 5; i++ ) 
        if ( !al.contains( i ) ) 
            al.add( i ); 

    // fill 2 
    for (int i = 0; i <= 10; i++ ) 
        if ( !al.contains( i ) ) 
            al.add( i ); 

    for( Integer i: al )
    {
        System.out.print( i + " ");     
    }

배열 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}을 얻을 수 있습니다.

주문을 보존하려면 사용하는 것이 가장 좋습니다. LinkedHashSet. 이 목록을 반복하여 삽입 쿼리로 전달하려면 주문이 보존되기 때문입니다.

이 시도

LinkedHashSet link=new LinkedHashSet();
List listOfValues=new ArrayList();
listOfValues.add(link);

이 전환은 목록을 반환하려고하지만 세트가 아닌 경우에 매우 도움이됩니다.

암호:

List<String> duplicatList = new ArrayList<String>();
duplicatList = Arrays.asList("AA","BB","CC","DD","DD","EE","AA","FF");
//above AA and DD are duplicate
Set<String> uniqueList = new HashSet<String>(duplicatList);
duplicatList = new ArrayList<String>(uniqueList); //let GC will doing free memory
System.out.println("Removed Duplicate : "+duplicatList);

메모: 확실히, 메모리 오버 헤드가있을 것입니다.

ArrayList<String> city=new ArrayList<String>();
city.add("rajkot");
city.add("gondal");
city.add("rajkot");
city.add("gova");
city.add("baroda");
city.add("morbi");
city.add("gova");

HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(city);
city.clear();
city.addAll(hashSet);
Toast.makeText(getActivity(),"" + city.toString(),Toast.LENGTH_SHORT).show();

If you are using model type List< T>/ArrayList< T> . Hope,it's help you.


Here is my code without using any other data structure like set or hashmap

  for(int i = 0; i < Models.size(); i++) {
     for(int j = i + 1; j < Models.size(); j++)  {           

       if(Models.get(i).getName().equals(Models.get(j).getName())){    
                                Models.remove(j);

                                j--;
                            }
                        }
                    }

LinkedHashSet will do the trick.

String[] arr2 = {"5","1","2","3","3","4","1","2"};
Set<String> set = new LinkedHashSet<String>(Arrays.asList(arr2));
for(String s1 : set)
    System.out.println(s1);

System.out.println( "------------------------" );
String[] arr3 = set.toArray(new String[0]);
for(int i = 0; i < arr3.length; i++)
     System.out.println(arr3[i].toString());

//output: 5,1,2,3,4

        List<String> result = new ArrayList<String>();
        Set<String> set = new LinkedHashSet<String>();
        String s = "ravi is a good!boy. But ravi is very nasty fellow.";
        StringTokenizer st = new StringTokenizer(s, " ,. ,!");
        while (st.hasMoreTokens()) {
            result.add(st.nextToken());
        }
         System.out.println(result);
         set.addAll(result);
        result.clear();
        result.addAll(set);
        System.out.println(result);

output:
[ravi, is, a, good, boy, But, ravi, is, very, nasty, fellow]
[ravi, is, a, good, boy, But, very, nasty, fellow]

This is used for your Custom Objects list

   public List<Contact> removeDuplicates(List<Contact> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            if (((Contact) o1).getId().equalsIgnoreCase(((Contact) o2).getId()) /*&&
                    ((Contact)o1).getName().equalsIgnoreCase(((Contact)o2).getName())*/) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);

    final List newList = new ArrayList(set);
    return newList;
}

you can use nested loop in follow :

ArrayList<Class1> l1 = new ArrayList<Class1>();
ArrayList<Class1> l2 = new ArrayList<Class1>();

        Iterator iterator1 = l1.iterator();
        boolean repeated = false;

        while (iterator1.hasNext())
        {
            Class1 c1 = (Class1) iterator1.next();
            for (Class1 _c: l2) {
                if(_c.getId() == c1.getId())
                    repeated = true;
            }
            if(!repeated)
                l2.add(c1);
        }

As said before, you should use a class implementing the Set interface instead of List to be sure of the unicity of elements. If you have to keep the order of elements, the SortedSet interface can then be used; the TreeSet class implements that interface.

for(int a=0;a<myArray.size();a++){
        for(int b=a+1;b<myArray.size();b++){
            if(myArray.get(a).equalsIgnoreCase(myArray.get(b))){
                myArray.remove(b); 
                dups++;
                b--;
            }
        }
}
import java.util.*;
class RemoveDupFrmString
{
    public static void main(String[] args)
    {

        String s="appsc";

        Set<Character> unique = new LinkedHashSet<Character> ();

        for(char c : s.toCharArray()) {

            System.out.println(unique.add(c));
        }
        for(char dis:unique){
            System.out.println(dis);
        }


    }
}
public Set<Object> findDuplicates(List<Object> list) {
        Set<Object> items = new HashSet<Object>();
        Set<Object> duplicates = new HashSet<Object>();
        for (Object item : list) {
            if (items.contains(item)) {
                duplicates.add(item);
                } else { 
                    items.add(item);
                    } 
            } 
        return duplicates;
        }
    ArrayList<String> list = new ArrayList<String>();
    HashSet<String> unique = new LinkedHashSet<String>();
    HashSet<String> dup = new LinkedHashSet<String>();
    boolean b = false;
    list.add("Hello");
    list.add("Hello");
    list.add("how");
    list.add("are");
    list.add("u");
    list.add("u");

    for(Iterator iterator= list.iterator();iterator.hasNext();)
    {
        String value = (String)iterator.next();
        System.out.println(value);

        if(b==unique.add(value))
            dup.add(value);
        else
            unique.add(value);


    }
    System.out.println(unique);
    System.out.println(dup);

If you want to remove duplicates from ArrayList means find the below logic,

public static Object[] removeDuplicate(Object[] inputArray)
{
    long startTime = System.nanoTime();
    int totalSize = inputArray.length;
    Object[] resultArray = new Object[totalSize];
    int newSize = 0;
    for(int i=0; i<totalSize; i++)
    {
        Object value = inputArray[i];
        if(value == null)
        {
            continue;
        }

        for(int j=i+1; j<totalSize; j++)
        {
            if(value.equals(inputArray[j]))
            {
                inputArray[j] = null;
            }
        }
        resultArray[newSize++] = value;
    }

    long endTime = System.nanoTime()-startTime;
    System.out.println("Total Time-B:"+endTime);
    return resultArray;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top