我有一个ArrayList<String>,我想从它中删除重复的字符串。我该怎么做呢?


当前回答

如果你想从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;
}

其他回答

如果你想保留你的Order,那么最好使用LinkedHashSet。 因为如果您想通过迭代将这个列表传递给一个插入查询,顺序将被保留。

试试这个

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

当您想返回List而不是Set时,这种转换将非常有用。

用于自定义对象列表

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


    }
}

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

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

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

Set<String> strSet = strList.stream().collect(Collectors.toSet());

是删除副本的最简单方法。