提问人:gojic 提问时间:6/5/2021 最后编辑:Zaingojic 更新时间:6/5/2021 访问量:60
在数组中查找重复值并删除它们?
Finding duplicated values in array and remove both of them?
问:
好的,我知道设置以及如何从列表中删除重复的项目,
Set<Integer> setint = new LinkedHashSet<>();
for(int j=0;j<selectedList.size();j++){
setint.add(selectedList.get(j));
}
但我需要的是删除它们。
例如,如果我有我需要的是找到重复的整数并删除这两个值。因此,对于此示例,我想删除 3 和 7,以便我有新的数组。1,2,3,3,4,5,6,7,7,8,9
1,2,4,5,6,8,9
答:
0赞
Elango
6/5/2021
#1
逻辑
前任:ar=[1,2,3,3,4,5,6,7,7,8,9]
首先将重复值复制到另一个数组并将其删除
现在你得到了ar_removed=[1,2,3,5,6,7,8,9]
这是你得到的另一个数组ar_dup=[3,7]
现在检查和ar_removed
ar_dup
您可以按条件删除值。结果ar_dup
ar_fi=[1,2,4,5,6,8,9]
愿它会有所帮助!
0赞
Zain
6/5/2021
#2
您可以将重复项添加到 中,然后用于删除所有重复项Set
list.removeAll(set)
ArrayList<Integer> list = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
add(3);
add(4);
add(5);
add(6);
add(7);
add(7);
add(7);
add(8);
add(9);
}};
// Sort the list to have adjacent duplicates
ArrayList<Integer> templist = new ArrayList<>(list);
Collections.sort(templist);
// Get the duplicate numbers
Set<Integer> duplicates = new HashSet<>();
for (int i = 0; i < templist.size() - 1; i++) {
if (templist.get(i).equals(templist.get(i + 1)))
duplicates.add(templist.get(i));
}
// Remove the duplicates
Log.d("LOG_TAG", "onCreate: " + list);
list.removeAll(duplicates);
Log.d("LOG_TAG", "onCreate: " + list);
结果:
D/LOG_TAG: onCreate: [1, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 9]
D/LOG_TAG: onCreate: [1, 2, 4, 5, 6, 8, 9]
评论