yash
yash

Reputation: 101

How to group identical strings in to any collection?

I have a string looks like

 {APP,LEE,APP,KCC,KCC,LEE,APP}.

I want to push same values like APP, LEE, KCC into different arraylists(any collection) respectively.

For example:

So that i can identify how many distinct groups are there and whats their value.

Thanks in advance.

Upvotes: 1

Views: 986

Answers (3)

BobTheBuilder
BobTheBuilder

Reputation: 19294

Use Map<String, List<String>>. Each value will contain a list of elements (you can use Integer to count if you want)

When you add an element:

List<String> elemList = myMap.get(key);
if (elemList == null){
    elemList = new ArrayList<String>;
    myMap.put(key, elemList);
}
elemList.add(key);

Although using counter is better...

    Map<String, Integer> myMap = new HashMap<>();
...
    Integer count = myMap.get(key);
    if (count == null){
        myMap.put(key, 1);
    } else {
        myMap.put(key, count + 1);
    }

Upvotes: 1

Chris Cooper
Chris Cooper

Reputation: 5122

It would be easiest to create a map with each list. Then if a key does not exit, create the entry it, then append.

Something like this:

Map<String, List<String>> result = new HashMap<String, List<String>>();

String[] values = source.substring(1, source.length() - 1).split(",");
for (String value : values) {
   List<String> existingMatches = result.get(value);
   if (existingMatches == null) {
     existingMatches = new ArrayList<String>();
     result.put(value, existingMatches);
   }
   existingMatches.add(value);
}

If you just need a count of the distinct values, replace the List with an AtomicInteger, and increment the value, then you end up with a map of distinct Strings, and a count of the num ber of times it appears.

Upvotes: 1

cowls
cowls

Reputation: 24344

You could instead create a Set from the ArrayList (This would remove duplicates) and then take the size of the set and each item of the set would be one group

Set<String> groups = new HashSet<String>(list);

groups.size(); //Number of groups

for(String group : groups) {
    System.out.println(group); //Print each value
}

Upvotes: 2

Related Questions