Header Ads Widget

Responsive Advertisement

Sorting Of a list multiple attribute wise two technique


Sorting a list by multiple attributes involves ranking items based on priority or weight assigned to each attribute. Two common techniques for sorting are Lexicographic Sorting and Weighted Sorting. Here's how each can be represented mathematically:


1. Lexicographic Sorting

This technique prioritizes attributes sequentially, similar to sorting words in a dictionary.

Math Representation:

Assume each item in the list has mmm attributes: \(A_{1}, A_{2}, ..., A_{m}\)​. The sorting function evaluates items \(X_{i}\) and \(X_{j}\) ​ as:

$$(X_{i} < X_{j}  if  A_{1,i} < A_{1,j} or (A_{1,i} = A_{1,j} and A_{2,i} < A_{2,j}))$$ and so on.

Steps:

  1. Compare items by the first attribute \(A_{1}\).
  2. If items tie on \(A_{1}\)​, compare on \(A_{2}\).
  3. Continue comparing until a distinction is found.

Example:

Sort a list of people by age, then by height:

Ø  Person 1: (Age = 25, Height = 5.9)

Ø  Person 2: (Age = 20, Height = 6.0)

Ø  Person 3: (Age = 25, Height = 5.8)

Sort order: Person 2 → Person 3 → Person 1.


2. Weighted Sorting

In weighted sorting, each attribute is assigned a weight indicating its importance, and a score is computed for each item. Sorting is done based on this score.

Math Representation:

Let \(w_{1}, w_{2}, ..., w_{m}\)​ ​ be the weights of attributes \(A_{1}, A_{2}, ..., A_{m}\)​​  such that:

\(w_{1}+ w_{2}+ ...+ w_{m}=1\)​ (weights normalized to 1).

The score \(S_{i}\)​ for item i is:

\(S_{i}=w_{1}\cdot A_{1,i}+w_{2}\cdot A_{2,i}+ ..., w_{m}\cdot A_{m,i}\)​


Sort items by descending \(S_{i}\)​

Example:

Sort cars by fuel efficiency and cost:

Ø  Car 1: (Fuel Efficiency = 30 MPG, Cost = $20,000)

Ø  Car 2: (Fuel Efficiency = 25 MPG, Cost = $18,000)

Ø  Car 3: (Fuel Efficiency = 35 MPG, Cost = $22,000)

Weights:

Ø  Fuel Efficiency: \(w_{1}=0.7\)

Ø  Cost: \(w_{2}=0.3\)

Scores:

Ø  Car 1: S=0.7×30+0.3×20000=21+6000=6021

Ø  Car 2: S=0.7×25+0.3×18000=17.5+5400=5417.5

Ø  Car 3: S=0.7×35+0.3×22000=24.5+6600=6624.5

Sort order: Car 3 → Car 1 → Car 2.


Comparison

Ø  Lexicographic Sorting is useful when attributes have strict precedence.

Ø  Weighted Sorting is better for scenarios where attributes contribute proportionally to the ranking.

 



 

Chained Comparator: Sorting Of a list multiple attribute wise two technique

First is multiple Class wise sorting

Collections.sort(list, new StaffMemberChainedComparator(

    new StaffMemberNameComparer(),

                new StaffMemberAgeComparator(),

                new StaffMemberSalaryComparator()

                )

        );

 

Single Class Comparator wise sorting

Collections.sort(list, new Comparator<Object>() {

   public int compare(Object obj1, Object obj2) {

   StaffMember e1 = (StaffMember) obj1;

   StaffMember e2 = (StaffMember) obj2;

    int name = e1.getName().compareTo(e2.getName());

    Integer ooo1 = new Integer(String.valueOf(e1.getAge()));

    Integer ooo2 = new Integer(String.valueOf(e2.getAge()));

    int age =  ooo1.compareTo(ooo2);

    int sal = Double.compare(e1.getSalary(), e2.getSalary());

          if (name != 0) { 

              return name; 

          }else if(name ==0 && age!=0){

            return age;

          }else if(name ==0 && age==0 && sal!=0){

             return sal;

          }

           

    return name;

   }

  });

 

 

 

Java

StaffMember

public class StaffMember {
    private String name;

    private int age;

    private double salary;

    /**
     * @return the StaffMember name
     */

   
public String getName() {

        return name;

    }

    /**
     * @param name the StaffMember name to set
     */

   
public void setName(String name) {

        this.name = name;

    }

    /**
     * @return the StaffMember age
     */

   
public int getAge() {

        return age;

    }

    /**
     * @param age the StaffMember age to set
     */

   
public void setAge(int age) {

        this.age = age;

    }

    /**
     * @return the StaffMember salary
     */

   
public double getSalary() {

        return salary;

    }

    /**
     * @param salary the StaffMember salary to set
     */

   
public void setSalary(double salary) {

        this.salary = salary;

    }

    /* (non-Javadoc)

     * @see java.lang.Object#hashCode()

     */

    @Override

    public int hashCode() {

        final int prime = 31;

        int result = 1;

        result = prime * result + age;

        result = prime * result + ((name == null) ? 0 : name.hashCode());

        long temp;

        temp = Double.doubleToLongBits(salary);

        result = prime * result + (int) (temp ^ (temp >>> 32));

        return result;

    }

    /* (non-Javadoc)

     * @see java.lang.Object#equals(java.lang.Object)

     */

    @Override

    public boolean equals(Object obj) {

        if (this == obj)

            return true;

        if (obj == null)

            return false;

        if (getClass() != obj.getClass())

            return false;

        StaffMember other = (StaffMember) obj;

        if (age != other.age)

            return false;

        if (name == null) {

            if (other.name != null)

                return false;

        } else if (!name.equals(other.name))

            return false;

        if (Double.doubleToLongBits(salary) != Double

                .doubleToLongBits(other.salary))

            return false;

        return true;

    }
}

 

 

Java

StaffMemberAgeComparator

import java.util.Comparator;


/**
 * This comparator compares two StaffMember by their ages.
 */

public class StaffMemberAgeComparator implements Comparator<StaffMember> {

    @Override

    public int compare(StaffMember staffMember1, StaffMember staffMember2) {

        return staffMember1.getAge() - staffMember2.getAge();

    }

}

 

 

Java

StaffMemberChainedComparator

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * This chained comparator facilitates the sorting of a list by various
 * attributes by connecting a sequence of individual field comparators.
 */

   
public class StaffMemberChainedComparator implements Comparator<StaffMember> {



        private List<Comparator<StaffMember>> listComparators;



        @SafeVarargs

        public StaffMemberChainedComparator(Comparator<StaffMember>... comparators) {

            this.listComparators = Arrays.asList(comparators);

        }



        @Override

        public int compare(StaffMember emp1, StaffMember emp2) {

            for (Comparator<StaffMember> comparator : listComparators) {

                int result = comparator.compare(emp1, emp2);

                if (result != 0) {

                    return result;

                }

            }

            return 0;

        }

}

 

 

Java

StaffMemberNameComparer

import java.util.Comparator;


public class StaffMemberNameComparer implements Comparator<StaffMember> {
   
    @Override

    public int compare(StaffMember arg0, StaffMember arg1) {

        return arg0.getName().compareTo(arg1.getName());

    }

}

 

 

Java

StaffMemberSalaryComparator

import java.util.Comparator;

/**
 * This comparator analyzes the salary differences between two staff members.
 */

public class StaffMemberSalaryComparator implements Comparator<StaffMember> {

    @Override

    public int compare(StaffMember staffMember1, StaffMember staffMember2) {

        int retval = Double.compare(staffMember1.getSalary(), staffMember2.getSalary());

        return retval;

    }

}

 

 

Java

StaffMemberSorting

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class StaffMemberSorting {

    public static void main(String[] args) {

        List<StaffMember> list = new ArrayList<StaffMember>();

        StaffMember emp = new StaffMember();

        emp.setName("kartik");

        emp.setAge(25);

        emp.setSalary(1000);

        list.add(emp);

        StaffMember emp2 = new StaffMember();

        emp2.setName("kartik");

        emp2.setAge(24);

        emp2.setSalary(5000);

        list.add(emp2);

        StaffMember emp3 = new StaffMember();

        emp3.setName("kartik");

        emp3.setAge(25);

        emp3.setSalary(5000);

        list.add(emp3);

        StaffMember emp4 = new StaffMember();

        emp4.setName("Hari");

        emp4.setAge(25);

        emp4.setSalary(1000);

        list.add(emp4);

        StaffMember emp5 = new StaffMember();

        emp5.setName("Hari");

        emp5.setAge(20);

        emp5.setSalary(2000);

        list.add(emp5);

        StaffMember emp6 = new StaffMember();

        emp6.setName("Hari");

        emp6.setAge(25);

        emp6.setSalary(500);

        list.add(emp6);

        StaffMember emp7 = new StaffMember();

        emp7.setName("Gopi");

        emp7.setAge(25);

        emp7.setSalary(500);

        list.add(emp7);

        Collections.sort(list, new StaffMemberChainedComparator(

                        new StaffMemberNameComparer(),

                        new StaffMemberAgeComparator(),

                        new StaffMemberSalaryComparator()

                )

        );

        System.out.println("Kartik many Class Design wise sorting");

        for (StaffMember staffMember : list) {

            System.out.println(staffMember.getName() + "---" + staffMember.getAge() + "---" + staffMember.getSalary());

        }

        System.out.println("Kartik Single Class Design wise sorting");

        Collections.sort(list, new Comparator<Object>() {

            public int compare(Object obj1, Object obj2) {

                StaffMember e1 = (StaffMember) obj1;

                StaffMember e2 = (StaffMember) obj2;

                int name = e1.getName().compareTo(e2.getName());

                Integer ooo1 = new Integer(String.valueOf(e1.getAge()));

                Integer ooo2 = new Integer(String.valueOf(e2.getAge()));

                int age = ooo1.compareTo(ooo2);

                int sal = Double.compare(e1.getSalary(), e2.getSalary());

                if (name != 0) {

                    return name;

                } else if (name == 0 && age != 0) {

                    return age;

                } else if (name == 0 && age == 0 && sal != 0) {

                    return sal;

                }


                return name;

            }

        });

        for (StaffMember staffMember : list) {

            System.out.println(staffMember.getName() + "---" + staffMember.getAge() + "---" + staffMember.getSalary());

        }

// JDK 1.8 Sort by name, then by age
List<StaffMember> sortedList = list.stream()
        .sorted(Comparator.comparing(StaffMember::getName)
                .thenComparing(StaffMember::getAge))
        .collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);

    }
}

 

 

This Java implementation demonstrates sorting a list of StaffMember objects using a chained comparator approach. You are sorting the staffmembers by multiple fields: name, age, and salary. Below is an explanation and breakdown of how the different classes work together.

Step-by-Step Breakdown:

Step 1: StaffMember Class

This class holds the details of a staffMember: name, age, and salary. It also overrides hashCode and equals methods for proper equality checking.

Ø  Fields: name, age, salary

Ø  Methods:

ü  getName(), getAge(), getSalary() – Getters for the fields.

ü  setName(), setAge(), setSalary() – Setters for the fields.

ü  hashCode() and equals() – For equality comparison based on employee properties.

Step 2: EmployeeSorting Class

This is the main driver class that sorts the Employee list using different comparator approaches.

  1. Adding Employees to List: Several Employee objects are added to the list with varying attributes like name, age, and salary.
  2. Chained Comparator Sorting:

ü  You use Collections.sort() to sort the list based on multiple comparators (name, age, and salary).

ü  The sorting is handled by the StaffMemberChainedComparator class which accepts a list of comparators (StaffMemberNameCompare, StaffMemberAgeComparator, StaffmemberSalaryComparator).

  1. Single Class Sorting:

ü  The sorting logic is implemented in a single anonymous comparator class inside the Collections.sort() method. It compares StaffMember objects first by name, then age, and finally salary.

Step 3: StaffMemberChainedComparator Class

This class implements Comparator<StaffMember> and enables chaining of multiple comparators.

Ø  Constructor: Accepts a var-args parameter of comparators.

Ø  compare Method: Loops through each comparator in the list and performs a comparison between two StaffMember objects. If one comparison is non-zero (i.e., a difference is found), it returns that result. Otherwise, it continues with the next comparator.

Step 4: SatffMemberNameCompare Class

This class implements Comparator<StaffMember> and compares two staff members by their name.

Ø  compare Method: Uses the String class’s compareTo method to compare the staff names lexicographically.

Step 5: StaffMemberAgeComparator Class

This class implements Comparator<StaffMember> and compares two staff members by their age.

Ø  compare Method: Performs subtraction between emp1.getAge() and emp2.getAge(). If the result is negative, emp1 is considered smaller; if positive, emp1 is larger.

Step 6: StaffMemberSalaryComparator Class

This class implements Comparator<StaffMember> and compares two staff members by their salary.

Ø  compare Method: Uses Double.compare() to compare the salary of two employees.

 

Example Output:

When sorting by multiple fields (name, age, and salary), the output will look something like this:

Chained Comparator Output:

Plaintext output

Gopi---25---500.0

Hari---20---2000.0

Hari---25---500.0

Hari---25---1000.0

Kartik---24---5000.0

Kartik---25---1000.0

Kartik---25---5000.0

 

Single Class Design Output:

Plaintext output

Gopi---25---500.0

Hari---20---2000.0

Hari---25---500.0

Hari---25---1000.0

Kartik---24---5000.0

Kartik---25---1000.0

Kartik---25---5000.0

 

In both sorting implementations, the list of employees is sorted first by name in ascending order, then by age in ascending order if the names are the same, and finally by salary.

 

Summary:

Ø  Chained Comparator: Flexible, reusable, and maintainable. You can easily change or add new fields to compare.

Ø  Single Class Comparator: Quick, but harder to maintain as you increase the number of fields to compare.

By chaining comparators, the sorting logic becomes modular and each comparator handles only one field. This is beneficial when dealing with large objects and complex comparison logic.



  

Single Class Comparator
Single Class Comparator


For More DSA Related information, visit

Ø  Bench mark of compiler using Ackerman function

Ø  Find the Missing Number

Ø  To check if the rows of a matrix are circularly identical in Java

Ø  how to check loop in array

Ø  100 door puzzle programs

Ø  Frequency Weaving Logic & Spiral Printing of a Rectangle

Ø  Zig Zag Matrix print multiple way

Ø  Gready Algorithm’s or knapsack algorithms

Ø  understanding recursive method for binary tree

Ø  Dynamic Programming: Max Square Sub-matrix of 1s in a Matrix

Ø  Previous and Next Date Palindrome

Ø  Karatsuba's Algorithm for multiplying two large numbers

Ø  Multiplication In different Way

Ø  Division by Different way

Ø  Time Analysis for Congested Routes Using Shortest Path Algorithms

Ø  Sorting of country

 

For More Java Related information, visit

Ø  Streams Lambdas Collectors and Functional Interfaces in Java 8

Ø  Java 8 support static method or default method or both in the interface

Ø  Inheritance Understand

Ø  Serialization understanding

Ø  Clone Under standing

Ø  Exception understanding

Ø  Garbage Collection Under Standing

Ø  How work Garbage Collection in Java

Ø  Under Standing Of Mutable and Immutable Class

Ø  enum understand

 

For Other information, visit

Ø  How to get the neighbor of binary tree

Ø  OWASP (Open Web Application Security Project)

Ø  Mastering Debounce, Throttle, Rate Limit & Backoff in Java

Ø  How to draw sequence diagram and other diagrams using plantuml

Ø  Pascal Triangle

Ø  Molecular weight of chemistry in Java code

Ø  String to xml or html Beautifier

Ø  Key Components of Apache Kafka for Scalable Messaging

Ø  Build a Video Stream Microservice with Kafka & REST API in Java

Ø  Kafka general questions and answers

 

 

Post a Comment

0 Comments