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