- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using TreeMap to sort User-defined Objects in Java
To sort user-defined object in Java, the code is as follows −
Example
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.
- Related Articles
- Using User-Defined Variables in MySQL
- Swap two Strings without using third user defined variable in Java
- User defined and custom exceptions in Java
- How to create a user defined exception (custom exception) in java?
- User-Defined Exceptions in Python
- User Defined Literals in C++
- PHP User-defined functions
- Sort arrays of objects in Java
- How to implement user defined exception in Python?
- How to create user defined exceptions in C#?
- User-defined Custom Exception in C#
- When should we create a user-defined exception class in Java?
- Get the maximum exam date using a user-defined variable in SQL
- User-defined Exceptions in Python with Examples
- User-defined Exceptions in C# with Example

Advertisements