Uso de TreeMap para ordenar objetos definidos por el usuario en Java

El ejemplo dado muestra cómo ordenar los objetos TreeMap definidos por el usuario, puede ordenar las claves según la lógica provista dentro del método.
Dado un registro de nombre y salario de los empleados como un número entero positivo, es necesario ordenar los registros en función del salario del empleado, utilizando TreeMap en Java . Si el salario es el mismo, use el nombre del empleado para comparar.

Ejemplos:

Input : xbnnskd 100 geek 50
Output : geek 50 xbnnskd 100

Input : shyam 50 ram 50
Output : ram 50 shyam 50
Explanation : 
As both the employees have equal pay, 
sorting is done on the basis of employee's name.

Acercarse:

1. Traverse through the string 
   and map the employee's salary(S)
   with the list of employee names having salary S.
2. Use a TreeMap to have 
   keys(Employee's Salary) in a sorted manner.
3. Now, Traverse through the map 
   and print the sorted records.

A continuación se muestra la implementación del enfoque anterior:

// Java program to print employees
// records in a sorted manner
  
import java.io.*;
import java.util.*;
  
public class GFG {
  
    // Function to sort the records
    static void sortRecords(String records)
    {
  
        // split the string
        // on the basis of delimiter space(" ")
        String[] rec = records.split(" ");
  
        // Create a Treemap to store
        // employee's salary with employee's name
        Map<Integer, ArrayList<String> > map = new TreeMap<>();
  
        // Traverse the records array
        // and store values in map
        for (int i = 1; i < rec.length; i += 2) {
  
            // Converting String to integer
            int sal = Integer.parseInt(rec[i]);
  
            String name = rec[i - 1];
  
            if (map.containsKey(sal)) {
  
                ArrayList<String> al = map.get(sal);
                al.add(name);
  
                // Sorting list of employees having Salary sal
                Collections.sort(al);
                map.remove(sal);
                map.put(sal, al);
            }
            else {
                ArrayList<String> al = new ArrayList<>();
                al.add(name);
                map.put(sal, al);
            }
        }
  
        // Traversing the map
        // to print the sorted records
        for (Map.Entry<Integer,
                       ArrayList<String> >
                 entry : map.entrySet()) {
  
            ArrayList<String> al1 = entry.getValue();
  
            for (int i = 0; i < al1.size(); i++)
                System.out.print(al1.get(i) + " "
                                 + entry.getKey() + " ");
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
       String records = "Harsh 100 Neha 100 Neha 20 Samay 600 Karan 50";
        // Calling function to sort the records
        sortRecords(records);
    }
}
Producción:

Neha 20 Karan 50 Harsh 100 Neha 100 Samay 600

Publicación traducida automáticamente

Artículo escrito por rachana soma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *