我有一个ArrayList<String>
,我想从其中删除重复的字符串。我怎样才能做到这一点?
如果你不希望在 "集合 "中出现重复,你应该考虑为什么要使用一个允许重复的 "集合"。删除重复元素的最简单方法是将内容添加到一个 "集合 "中(不允许重复),然后再将 "集合 "添加到 "数组列表 "中。
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
当然,这破坏了ArrayList
中元素的排序。
在Java 8中。
List<String> deduped = list.stream().distinct().collect(Collectors.toList());
请注意,列表成员的hashCode-e-quals合同应该得到尊重,以使过滤正常工作。
1:
假设我们有一个像String
的列表。
List<String> strList = new ArrayList<>(5);
// insert up to five items to list.
那么我们可以通过多种方式删除重复的元素。
List<String> deDupStringList = new ArrayList<>(new HashSet<>(strList));
注意:如果我们想保持插入顺序,那么我们需要使用LinkedHashSet
代替HashSet
。
使用番石榴
List<String> deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));
List<String> deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());
注意:如果我们想在一个特定的列表实现中收集结果,如
LinkedList
,那么我们可以将上面的例子修改为:
List<String> deDupStringList3 = strList.stream().distinct()
.collect(Collectors.toCollection(LinkedList::new));
。
List<String> deDupStringList3 = strList.stream().distinct()
.collect(Collectors.toCollection(LinkedList::new));
我们也可以在上面的代码中使用 "parallelStream",但它可能不会带来预期的性能优势。 请看这个[问题][1]了解更多。
[1]: https://stackoverflow.com/questions/53645037/will-parallel-stream-work-fine-with-distinct-operation
这里有一个不影响你的列表排序的方法'。
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流提供了一种非常简单的方法来从列表中删除重复的元素。 使用 distinct 方法。 如果我们有一个城市列表,我们想从该列表中删除重复的元素,可以用一行来完成-------。
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());
[如何从数组列表中删除重复的元素][1]
[1]: http://netjs.blogspot.com/2015/08/how-to-remove-duplicate-elements-from-arraylist-java.html
还有[Guava][2]中的[ImmutableSet
][1]作为一个选项([这里][3]是文档)。
ImmutableSet.copyOf(list);
[1]: https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/ImmutableSet.html [2]: https://github.com/google/guava [3]: https://github.com/google/guava/wiki/ImmutableCollectionsExplained
可以在不使用HashSet或多一个数组的情况下,从数组列表中删除重复的内容。
试试这段代码。
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;
}
可能有点矫枉过正,但我喜欢这种孤立的问题。 :)
这段代码使用了一个临时的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
}
}
EDIT: 我想,通用的东西并没有真正增加任何价值在这里... ... 哦,好吧。 :)
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);
}
如果你愿意使用第三方库,你可以使用 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();
注:我是Eclipse Collections的提交人。
1:
代码:
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时,对每个元素使用一个条件。 例如:
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 + " ");
}
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}。
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();
T>/ArrayList< T>/ArrayList<。 希望对你有所帮助。
这是我的代码,没有使用任何其他数据结构,如集合或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--;
}
}
}