Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicate strings in list and make them unique

I have an ArrayList with duplicate string values and want to make the duplicates unique by appending a count.

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("b");
    list.add("c");
    list.add("a");
    list.add("a");
    list.add("a");

    HashSet<String> set = new HashSet<String>();
    List<String> duplicateList = new ArrayList<String>();

    for (String item : list) {
        // If String is not in set, add it to the list and the set.
        if (!set.contains(item)) {              
            set.add(item);
        } else {
            duplicateList.add(item);
        }
    }

    for (String element : duplicateList) {
        System.out.println(element);
    }
}

Is there any way to make the list like:

a
b
c
d
b1
c1
a1
a2
a3
like image 984
user2196474 Avatar asked Nov 26 '16 08:11

user2196474


1 Answers

You can use Java with Hashing O(n)

Here l is input List

public static List getUniqueList(List<String> l){
    HashMap<String,Integer> hm=new HashMap<String,Integer>();
    for(int i=0;i<l.size();i++) {
        String key=l.get(i);
        if(hm.containsKey(key)) {
            l.set(i, key+hm.get(key));
            hm.put(key,hm.get(key)+1);
        }else { 
            //newl.add(key);
            hm.put(key,1);
        }
    }
return l;
}
like image 114
ashutosh pandey Avatar answered Oct 24 '22 21:10

ashutosh pandey