Shawn
Shawn

Reputation: 13

How to GROUP BY same strings in Java

I have got an Arraylist of strings and I need to return the Arraylist indexes of strings that are the same.

For example

Arraylist[0]: IPAddress

Arraylist[1]: DomainName

Arraylist[2]: IPAddress

Arraylist[3]: Filesize

The output should be:

Arraylist[0]
IPAddress|0,2 //0,2 denotes the arraylist index that is of the same

Arraylist[1]
DomainName|1

Arraylist[2]
Filesize|3

Any idea how can this be achieved?

What I have done is:

for(int i=0; i<arr.size(); i++){
   if(arr.get(i).equals(arr.size()-1)){
      //print index


   }
}

Upvotes: 0

Views: 475

Answers (2)

Saravana
Saravana

Reputation: 12817

With Java8 streams

    List<String> strings = Arrays.asList("IPAddress", "DomainName", "IPAddress", "Filesize");
    Map<String, List<Integer>> map = IntStream.range(0, strings.size()).boxed().collect(Collectors.groupingBy(strings::get));
    System.out.println(map);

output

{DomainName=[1], Filesize=[3], IPAddress=[0, 2]}

To get the results in ordered

    Map<String, List<Integer>> map = IntStream.range(0, strings.size())
                                    .boxed()
                                    .collect(Collectors.groupingBy(strings::get, LinkedHashMap::new, Collectors.toList()));

Upvotes: 1

Makoto
Makoto

Reputation: 106460

The mechanical steps are fairly straightforward:

  • Get a collection which can support a key (which is the string in your list) and a list of values representing the indexes in which they occur (which would be another ArrayList).
  • If the element exists in the collection, simply add the index to its value.
  • Otherwise, create a new list, add the index to that, then add that to the collection.

Here is some sample code below.

final List<String> list = new ArrayList<String>() {{
    add("IPAddress");
    add("DomainName");
    add("IPAddress");
    add("Filesize");
}};

final Map<String, List<Integer>> correlations = new LinkedHashMap<>();
for (int i = 0; i < list.size(); i++) {
    final String key = list.get(i);
    if (correlations.containsKey(key)) {
        correlations.get(key).add(i);
    } else {
        final List<Integer> indexList = new ArrayList<>();
        indexList.add(i);
        correlations.put(key, indexList);
    }
}

Any optimizations to the above are left as an exercise for the reader.

Upvotes: 0

Related Questions