我有一个 ArrayList<String>, 我要删除重复的字符串。我怎么可以这样做?

有帮助吗?

解决方案

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

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

当然,这会破坏<=>中元素的排序。

其他提示

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

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

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

在Java 8中:

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

请注意合同,以使过滤正常工作。

如果您不想复制,请使用设置而不是List。要将Set转换为<=>,您可以使用以下代码:

// list is some List of Strings
Set<String> s = new HashSet<String>(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是没有重复项目的列表 (确保YourClass根据你想要的平等方式使用equals方法)

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 来自 Guava 作为选项(此处是文档):

ImmutableSet.copyOf(list);

可以在不使用 HashSet 多一个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;
}

可能有点过分,但是我享受这种孤立的问题。:)

这个代码使用一个临时设置(为的独特性检查),但删除元件的直接原来的名单。由于元件的清除内部的对列表可以促使大量的阵列复制,删除(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);
    }
}

虽然我们在这,这里有一个版本链表(很多好!):

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()方法。 rel =“nofollow”> Eclipse Collections (以前是GS Collections)。

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

注意:我是Eclipse Collections的提交者。

这三行代码可以从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 。 因为如果要通过迭代将此List传递给插入查询,则会保留该顺序。

试试这个

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

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

<强>代码:

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

如果您使用的是型号List&lt; T&GT; / ArrayList的&LT; T&GT; 。希望,它对你有帮助。


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

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

        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]

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

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

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

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

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

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

如果要从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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top