[英]How would I remove duplicates from an Arraylist<Integer[]>? (Java)
问题真的说明了一切。 我尝试使用 LinkedHashSet 但没有奏效。 如果我没有错,那么由于比较 Integer arrays,比较没有正确完成。
我的目标是创建一个 static 方法 removeDuplicates(ArrayList<Integer>)。 该方法应根据 arrays 的内容进行比较。 到目前为止我的尝试:
import java.util.ArrayList;
import java.util.LinkedHashSet;
public class test {
public static void main(String[] args) {
ArrayList<Integer[]> arrayList = new ArrayList<>();
Integer[] array1 = new Integer[2];
array1[0] = 1;
array1[1] = 4;
Integer[] array2 = new Integer[2];
array2[0] = 1;
array2[1] = 4;
arrayList.add(array1);
arrayList.add(array2);
LinkedHashSet<Integer[]> hashSet = new LinkedHashSet<>(arrayList);
ArrayList<Integer[]> listWithoutDuplicates = new ArrayList<>(hashSet);
System.out.println("Number of elements before using linkedhashset: " + arrayList.size());
System.out.println("number of elements after: (expecting 1) " + listWithoutDuplicates.size());
}
}
给出结果:
Number of elements before using linkedhashset: 2
number of elements after (expecting 1): 2
一种可能的解决方案是保存列表中每个数组中每个数字的出现次数以考虑重复数字,并检查此实例是否已添加:
private static List<Integer[]> removeDuplicates(List<Integer[]> list) {
List<HashMap<Integer,Integer>> instances = new ArrayList<>();
List<Integer[]> res = new ArrayList<>();
for(Integer[] arr : list) {
HashMap<Integer,Integer> map = new HashMap<>();
for(Integer num : arr) {
if(map.containsKey(num))
map.replace(num, map.get(num)+1);
else
map.put(num,1);
}
if(!instances.contains(map)) {
instances.add(map);
res.add(arr);
}
}
return res;
}
您可以使用以下方法
List<Integer[]> listWithoutDuplicates = arrayList.stream()
.map(arr -> Arrays.asList(arr))
.distinct()
.map(list -> list.toArray(new Integer[0]))
.collect(Collectors.toList());
这里的技巧是,将Integer[]
映射到List<Integer>
允许您利用List::equals()
方法来检测两个 List 是否相等(=“都包含相同顺序的相同元素”)。 结合Stream::distinct()
将切断重复,然后将每个唯一的List
转换回Integer[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.