I have a list with values {"16","b","c","d","e","16","f","g","16","b"}; In this 16 and b are repeated so i want to delete all the entries of them and i need output as c, d, e, f, g. Below program works fine. Any better solutions?
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;
}
}
removeDupsshould really be calledfindDupsbecause it doesn't actually remove anything; it just finds the items that are duplicated. If the linel.removeAll(ll)were moved inside ofremoveDups, thenremoveDupswould actually merit that name.O(n), You can do better by using Hash maps.oncein the list.