Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate entries from ArrayList according to first char of string

Tags:

java

arraylist

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.

like image 703
Prateek Avatar asked Nov 24 '25 15:11

Prateek


2 Answers

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]

like image 192
harsh Avatar answered Nov 26 '25 04:11

harsh


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));
        }
    }

}
like image 41
peter.petrov Avatar answered Nov 26 '25 05:11

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!