I want to remove a string from an array list whose first character is the same as another string's.
Example
List<String> collection = new ArrayList<String>();
collection.add("1 w a");
collection.add("2 r a");
collection.add("1 r b");
collection.add("2 r b");
collection.add("3 w a");
Output
collection = ["1 w a", "2 r a", "3 w a"]
I tried using hashset and linkedhashset.
With minimal storage of first character, you can do find-and-remove-dups:
List<Character> dups = new ArrayList<Character>();
Iterator<String> itr = collection.iterator();
while(itr.hasNext()) {
String s = itr.next();
char c = s.charAt(0);
if(dups.contains(c)) {
itr.remove();
continue;
}
dups.add(c);
}
System.out.println(collection);
Output:
[1 w a, 2 r a, 3 w a]
The ind list contains the indices to be removed.
But the people commenting above are right, computationally i.e. algorithmically viewed, you should use a better data structure here, rather than ArrayList.
import java.util.ArrayList;
import java.util.List;
public class Test005 {
public static void main(String[] args) {
List<String> collection = new ArrayList<String>();
collection.add("1 w a");
collection.add("2 r a");
collection.add("1 r b");
collection.add("2 r b");
collection.add("3 w a");
List<Integer> ind = new ArrayList<Integer>();
for (int i=0; i<collection.size(); i++){
for (int j=0; j<i; j++){
if (collection.get(j).charAt(0) == collection.get(i).charAt(0)){
ind.add(i);
break;
}
}
}
for (int k=0; k<ind.size(); k++){
collection.remove(ind.get(k).intValue());
}
for (int i=0; i<collection.size(); i++){
System.out.println(collection.get(i));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With