首页 文章

如何从ArrayList中删除重复的元素?

提问于
浏览
432

我有 ArrayList<String> ,我想从中删除重复的字符串 . 我怎样才能做到这一点?

30 回答

  • 20

    这用于您的自定义对象列表

    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;
    }
    
  • 0

    在Java 8中:

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

    请注意,应尊重列表成员的hashCode-equals Contract ,以使过滤正常工作 .

  • 107

    假设我们有一个 String 列表:

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

    然后我们可以通过多种方式删除重复的元素 .

    Java 8之前

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

    Note: 如果我们想维护插入顺序,那么我们需要使用 LinkedHashSet 来代替 HashSet

    使用 Guava

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

    使用Java 8

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

    Note: 如果我们想在 specific list implementation 中收集结果,例如 LinkedList 然后我们可以将上面的例子修改为:

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

    我们也可以在上面的代码中使用 parallelStream 但它可能不会给出预期的性能优势 . 请查看question以获取更多信息 .

  • 0

    这可以解决问题:

    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;
    }
    
  • 24
    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();
    
  • 0

    如果您想保留您的订单,那么最好使用 LinkedHashSet . 因为如果要通过迭代将此List传递给插入查询,则会保留该顺序 .

    试试这个

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

    当您想要返回List但不返回Set时,此转换将非常有用 .

  • 39

    虽然将 ArrayList 转换为 HashSet 可以有效地删除重复项,但如果您需要保留插入顺序,我建议您使用此变体

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

    然后,如果需要返回 List 引用,则可以再次使用转换构造函数 .

  • 2
    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]
    
  • 12

    这三行代码可以从ArrayList或任何集合中删除重复的元素 .

    List<Entity> entities = repository.findByUserId(userId);
    
    Set<Entity> s = new LinkedHashSet<Entity>(entities);
    entities.clear();
    entities.addAll(s);
    
  • 27

    填充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}

  • 3

    这是一种不影响列表排序的方式:

    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是没有重复项目的列表(确保YourClass根据你想要的平等对应的方法)

  • 2

    如果您愿意使用第三方库,则可以使用Eclipse Collections(以前的GS Collections)中的方法 distinct() .

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

    使用 distinct() 而不是转换为Set然后返回到List的优点是 distinct() 保留了原始List的顺序,保留了每个元素的第一次出现 . 它是通过使用Set和List实现的 .

    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;
    

    如果无法将原始List转换为Eclipse Collections类型,则可以使用ListAdapter获取相同的API .

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

    Note: 我是Eclipse Collections的提交者 .

  • 5

    可能有点矫枉过正,但我喜欢这种孤立的问题 . :)

    此代码使用临时Set(用于唯一性检查),但直接删除原始列表中的元素 . 由于ArrayList中的元素移除会导致大量的数组复制,因此避免了remove(int)方法 .

    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);
        }
    }
    

    虽然我们在这里,但这里是LinkedList的一个版本(好多了!):

    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();
            }
        }
    }
    

    使用标记界面为List提供统一的解决方案:

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

    编辑:我想泛型的东西在这里并没有真正增加任何 Value ..哦,好吧 . :)

  • 1
    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;
            }
    
  • 274

    LinkedHashSet可以解决这个问题 .

    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());
    

    //输出:5,1,2,3,4

  • 0
    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--;
                }
            }
    }
    
  • 10

    如果要从ArrayList中删除重复项,请找到以下逻辑,

    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;
    }
    
  • 1

    可以在不使用 HashSetone more 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]
    
  • 1

    来自GuavaImmutableSet作为选项(here是文档):

    ImmutableSet.copyOf(list);
    
  • 0

    如果使用的是模型类型List <T> / ArrayList <T> . 希望,它对你有所帮助 .


    这是我的代码,不使用任何其他数据结构,如set或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--;
                                }
                            }
                        }
    
  • 50

    您也可以这样做,并保留顺序:

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

    如前所述,您应该使用实现Set接口而不是List的类来确保元素的唯一性 . 如果必须保持元素的顺序,则可以使用SortedSet接口; TreeSet类实现该接口 .

  • 22

    你可以在下面使用嵌套循环:

    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);
            }
    
  • 22
    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);
    }
    
  • 9

    Code:

    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);
    

    Note: 肯定会有内存开销 .

  • 892
    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);
    
  • 2
    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);
            }
    
    
        }
    }
    
  • 1

    如果你不想在 Collection 中重复,你应该考虑为什么你使用允许重复的 Collection . 删除重复元素的最简单方法是将内容添加到 Set (不允许重复),然后将 Set 添加回 ArrayList

    List<String> al = new ArrayList<>();
    // add elements to al, including duplicates
    Set<String> hs = new HashSet<>();
    hs.addAll(al);
    al.clear();
    al.addAll(hs);
    

    当然,这会破坏 ArrayList 中元素的排序 .

  • 1

    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());
    

    How to remove duplicate elements from an arraylist

  • 1

    如果您不想重复,请使用Set而不是 List . 要将 List 转换为 Set ,您可以使用以下代码:

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

    如果真的有必要,你可以使用相同的结构将 Set 转换回 List .

相关问题