Use Collections.sort to sort custom class and user defined Comparator : Collections « Collections Data Structure « Java






Use Collections.sort to sort custom class and user defined Comparator

   

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

class Employee implements Comparable {
  private String name;

  private double salary;

  Employee(String name, double salary) {
    this.name = name;
    this.salary = salary;
  }

  String getName() {
    return name;
  }

  double getSalary() {
    return salary;
  }

  public String toString() {
    return "Name = " + getName() + ", Salary = " + getSalary();
  }

  public int compareTo(Object o) {
    if (!(o instanceof Employee))
      throw new ClassCastException();

    Employee e = (Employee) o;

    return name.compareTo(e.getName());
  }

  static class SalaryComparator implements Comparator {
    public int compare(Object o1, Object o2) {
      if (!(o1 instanceof Employee) || !(o2 instanceof Employee))
        throw new ClassCastException();

      Employee e1 = (Employee) o1;
      Employee e2 = (Employee) o2;

      return (int) (e1.getSalary() - e2.getSalary());
    }
  }
}

class UtilDemo4 {
  public static void main(String[] args) {
    String[] names = { "A", "B", "C", "D" };

    double[] salaries = { 2.0, 5.0, 6.0, 4.0 };

    List l = new ArrayList();

    for (int i = 0; i < names.length; i++)
      l.add(new Employee(names[i], salaries[i]));

    Collections.sort(l);

    ListIterator liter = l.listIterator();

    while (liter.hasNext())
      System.out.println(liter.next());

    Collections.sort(l, new Employee.SalaryComparator());

    liter = l.listIterator();

    while (liter.hasNext())
      System.out.println(liter.next());
  }
}

   
    
    
  








Related examples in the same category

1.Collections.min with Comparator
2.Minimum and maximum number in array
3.Shuffling the Elements of a List or Array: use Collections.shuffle() to randomly reorder the elements in a list
4.Shuffle the elements in the array
5.Create an empty collection object
6.Collections.reverse
7.Collections.shuffle to shuffle a list
8.Collections.fill
9.Demonstrates the use of final collections
10.Use Collections.shuffle to shuffle listUse Collections.shuffle to shuffle list
11.Making a Collection Read-Only
12.Shuffle generic list
13.Create List containing n Copies of Specified Object Example
14.Create and demonstrate an immutable collection.
15.Sort and Search a LinkedList.
16.Finding an Element in a Sorted List
17.Use reverse(), rotate(), and shuffle().
18.This program demonstrates the random shuffle and sort algorithmsThis program demonstrates the random shuffle and sort algorithms