How do I remove repeated elements from ArrayList?

后端 未结 30 1712
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

相关标签:
30条回答
  • 2020-11-21 06:50
    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 讨论(0)
  • 2020-11-21 06:52

    In Java 8:

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

    Please note that the hashCode-equals contract for list members should be respected for the filtering to work properly.

    0 讨论(0)
  • 2020-11-21 06:52

    If you want to preserve your Order then it is best to use LinkedHashSet. Because if you want to pass this List to an Insert Query by Iterating it, the order would be preserved.

    Try this

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

    This conversion will be very helpful when you want to return a List but not a Set.

    0 讨论(0)
  • 2020-11-21 06:54

    This three lines of code can remove the duplicated element from ArrayList or any collection.

    List<Entity> entities = repository.findByUserId(userId);
    
    Set<Entity> s = new LinkedHashSet<Entity>(entities);
    entities.clear();
    entities.addAll(s);
    
    0 讨论(0)
  • 2020-11-21 06:57

    When you are filling the ArrayList, use a condition for each element. For example:

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

    We will get an array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

    0 讨论(0)
  • 2020-11-21 06:58
    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--;
                }
            }
    }
    
    0 讨论(0)
提交回复
热议问题