我有一个值为{“16”,“b”,“c”,“d”,“e”,“16”,“ F”, “G”, “16”, “b”}; 在这16和b重复,所以我想删除它们的所有条目,我需要输出为c,d,e,f,g。以下程序正常工作。有更好的解决方案如何删除一个元素的所有发生如果它在一个arraylist中重复
public class Test {
public static void main(String[] args) {
ArrayList <String> l = new ArrayList <String>();
String[] str = {
"16",
"b",
"c",
"d",
"e",
"16",
"f",
"g",
"16",
"b"
};
for (String s: str) {
l.add(s);
}
List ll = removeDups(l);
l.removeAll(ll);
System.out.println("Final List " + l);
}
private static List <String> removeDups(ArrayList <String> l) {
List <String> ll = new ArrayList <String>();
for (String a: l) {
int x = Collections.frequency(l, a);
if (x > 1) {
ll.add(a);
}
}
return ll;
}
}
请在发布Stackoverflow问题之前解释代码或发表评论。它帮助每个人。 –
实际上,'removeDups'方法实际上应该称为'findDups',因为它实际上并没有删除任何东西;它只是_finds_重复的项目。如果'l.removeAll(ll)'这一行被移到'removeDups'内,那么_then_'removeDups'实际上会有这个名字。 –
考虑Collections.frequency的命令是'O(n)',你可以使用Hash地图做得更好。 –