tags:

views:

58

answers:

3

Hi All ! I am having one problem in java arraylist. I am good in databases :) We normally use "group by" to group rows. I want the same thing but in java for one of my project I have following format in arraylist

name1:val1
name1:val2
name1:val3
name2:val8
name2:val7
name7:val54
name7:val76
name7:val34

I want to convert this arraylist to give me following output:

-name1
  val1
  val2
  val3
-name2
  val8
  val7
-name7
    .
    .
    .
  val34

this is not a school assignment :). may be for some of Java Guru it looks like a small thing to do.

A: 

What you are looking for is called multi-map.

There is no standard multi-map in java.util, but Google collections has implemented it -> here. The project home page is here

Alexander Pogrebnyak
+1  A: 

Use a Map<String, List<Integer>>. You could use the following snippets:

// declare
Map<String, List<Integer>> m = new HashMap<String, List<Integer>>();

// insert into the structure the pair 'a':2 
List<Integer> l = m.get("a");
if ( l == null ) {
  l = new ArrayList<Integer>();
  m.put("a", l);
}
l.add(2);

// iterate over the values
for (Map<String, List<Integer>>.Entry e : m) {
  System.out.println("-" + e.getKey());
  for (Integer i : m.getValue()) {
    System.out.println(" " + i);
  }
}
rmarimon
+2  A: 

I like to do that kind of thing with a map.

import java.util.*;

public class DoIt {
    public static void main(String[] args) {
         List l = new ArrayList<String>();
         l.add("name1:val1");
         l.add("name1:val2");
         l.add("name1:val3");
         l.add("name1:val4");
         l.add("name2:val1");
        Map results = new HashMap<String,String>();
        for (Iterator i = l.iterator(); i.hasNext();) {
             String s = (String)i.next();
             String[] tmp = s.split(":");
             if (!results.containsKey(tmp[0])) {
                 System.out.println("-"+tmp[0]+"\n"+tmp[1]);
                results.put(tmp[0], tmp[1]);
             } else {
                 System.out.println(tmp[1]);
             }
         }
     }
}
jskaggz
WOWyou are awesome !Let me try and I will get back to you :)