Using TreeMap to sort User-defined Objects in Java

JavaServer Side ProgrammingProgramming

To sort user-defined object in Java, the code is as follows −

Example

 Live Demo

import java.io.*;
import java.util.*;
public class Demo{
   static void sort_objects(String my_data){
      String[] my_vals = my_data.split(" ");
      Map<Integer, ArrayList<String> > my_map = new TreeMap<>();
      for (int i = 1; i < my_vals.length; i += 2){
         int my_age = Integer.parseInt(my_vals[i]);
         String name = my_vals[i - 1];
         if (my_map.containsKey(my_age)){
            ArrayList<String> my_list = my_map.get(my_age);
            my_list.add(name);
            Collections.sort(my_list);
            my_map.remove(my_age);
            my_map.put(my_age, my_list);
         }
         else{
            ArrayList<String> my_list = new ArrayList<>();
            my_list.add(name);
            my_map.put(my_age, my_list);
         }
      }
      for (Map.Entry<Integer, ArrayList<String> > entry : my_map.entrySet()){
         ArrayList<String> al1 = entry.getValue();
         for (int i = 0; i < al1.size(); i++)
         System.out.print(al1.get(i) + " " + entry.getKey() + " ");
      }
   }
   public static void main(String args[]){
      String my_obj = "Joe 36 Hannah 24 Jill 13 Jack 1 Preet 8 Deep 45";
      System.out.println("The objects after sorting are : ");
      sort_objects(my_obj);
   }
}

Output

The objects after sorting are :
Jack 1 Preet 8 Jill 13 Hannah 24 Joe 36 Deep 45

A class named Demo contains a function named ‘sort_objects’ creates a hashmap that maps the integer and the array list. It iterates through the values, and checks to see which is a string and which is an integer element and these are sorted based on integer values. In the main function, the string object is created and the function is called on this string object and relevant message is displayed on the console.

raja
Published on 09-Jul-2020 06:41:51
Advertisements