What would be a cleaner way to cluster ArrayList() based on one column data?

Sushant :

Say I have a below list

 full_list

 ID     NAME
 1      Apple
 1      Banana
 2      Carrot
 1      Mango
 2      Spinach
 3      BMW
 3      Opal

With this single list, I want to create a grouped list based on column ID like below

 fruits_list              veggies_list               cars_list
 ID      NAME             ID      NAME              ID     NAME
 1       Apple            2       Carrot            3      BMW
 1       Banana           2       Spinach           3      Opal
 1       Mango

I was trying to do it with Arraylist<ArrayList<CustomObject>>. But it is adding more complexity to the code. Am I doing it wrong? Is there any cleaner way to do this?

PS: Data incoming is not fixed. I cannot define lists explicitly with conditions (i.e. if(id==1), if(id==2) etc). This shall be done dynamically based on incoming data.

Sushant :

Thanks all for your answers. As @Mauron advised, I used Collectors.groupingby and it saved literally 20 lines of sorting code. After some research I found how to list all keys in map here

So here is the solution I was looking for

 //Create a grouped map using Collectors.groupingBy 
 Map m = itemslist.stream().collect(Collectors.groupingBy(ShipmentItemsModel::getLrid));
 //Make an ArrayList of keys
 ArrayList<Integer> keys = new ArrayList<>(m.keySet());
  //Use enhanced for loop (foreach) to go through each key in order to create list of items each key has.
  //(In Layman terms: It will create small lists based on keys)  
  for (int singlekey: keys) {
         ArrayList<ShipmentItemsModel> values = new ArrayList<ShipmentItemsModel>();
            values = (ArrayList<ShipmentItemsModel>) m.get(singlekey);
            for (ShipmentItemsModel sortedmodel: values) {
                System.out.println("Key/ID :"+singlekey+" and values :"+sortedmodel.getProductname());
            }
        }

So final output will be like this

 Key/ID :1 and value :Apple
 Key/ID :1 and value :Banana
 Key/ID :1 and value :Mango
 Key/ID :2 and value :Carrot
 Key/ID :2 and value :Spinach
 Key/ID :3 and value :BMW
 Key/ID :3 and value :Opal

I appreciate all the answers. Thanks all once again.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310177&siteId=1