3

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.

4
  • You could use a Map, mapping first chars to Strings although this may be overkill. Commented Nov 25, 2013 at 9:44
  • @Quirliom thanks. but i want to use ArrayList. Commented Nov 25, 2013 at 9:47
  • fill another ArrayList using this, and in a step add the first character to a separate Set and check the list for the next string's first character at each step. let me know if you are not getting the point clearly. Commented Nov 25, 2013 at 9:48
  • @Prateek but an ArrayList is the wrong data structure for this kind of task Commented Nov 25, 2013 at 9:54

6 Answers 6

1

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]

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

1

Use a TreeSet with a Comparator that only looks at the first character. Insert all elements into the set.

 new TreeSet<String>(
   new Comparator<String>(){
     public int compare(String s1, String s2){
         if (s1 == null || s1.length() == 0)
            return (s2 == null || s2.length() == 0) ? 0 : 1;
         else if (s2 == null || s2.length == 0)
            return -1;
         else 
            return s1.substring(0,1).compareTo(s2.substring(0,1));
     }
 });

1 Comment

A TreeSet operates like any other Set in that it only allows one element that it considers to be "equal". The Comparator I provide, only looks at the first character of the String. It has some added complexity to handle the null / empty case. By providing this Comparator to the TreeSet, the Set will only keep the first String with a unique first character. Now simply add you collection of elements to the set.
1

Essentially what you want to do is go through the list and for each element, go through the rest of the list and delete any that have the same startign character.

A sample implementation:

List<String> deleteList = new ArrayList<String>();
for(int i = 0;i < collection.size();i ++){
    //If this is flagged for deletion continue
    if(deleteList.contains(collections.get(i)))continue; 
    for(int j = i + 1;j < collection.size();j ++){
        //If this is flagged for deletion continue
        if(deleteList.contains(collections.get(j)))continue;
        //If the chars are the same, add it to the list to be deleted
        if(collection.get(i).charAt(0) == collection.get(j).charAt(0)){
            deleteList.add(collection.get(j));
        }
    } 
}

collection.removeAll(deleteList);

Comments

0
 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");

    Set set = new HashSet();
    for(int i=0;i<collection.size();++i){
        String temp = collection.get(i);
        if(set.contains(temp.charAt(0))){
            collection.remove(temp);
            i--;
        }  else{
            set.add(temp.charAt(0));
        }
    }
    for(int i=0;i<collection.size();++i){
        System.out.println(collection.get(i));
    }

output :

1 w a

2 r a

3 w a

Comments

0

Going through every element of given List, With the help of a temporary set we are checking if the first element is in the set. if it is not then we are adding it in the final list. if it already contains that, then skip it.

import java.util.*;
public class Test {

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");
    System.out.println(removeDuplicates(collection));
}

private static List<String> removeDuplicates(List<String> collection) {

    HashSet<String> withoutDuplicates = new HashSet<String>();
    List<String> collection2 = new ArrayList<String>();
    for(String s : collection){
        String[]  temp = s.split(" ");

        if(!withoutDuplicates.contains(temp[0])){
            withoutDuplicates.add(temp[0]);
            collection2.add(s);
        }
    }
    return collection2;
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.