Core Java

Five useful ways to sorting in java

A rapid overview of java sorting :
 
 
 
 
 
 
 
 
 
 

normal sort of list :

  private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry");
  Collections.sort(VEGETABLES);

  output: apple, blackberry, cocumbers 
  

Reverse sorting:

  private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry");
  Collections.sort(VEGETABLES, Collections.reverseOrder());
  output: cocumbers, blackberry, apple
  

with custom comparator:

  private class StringComparator implements Comparator {
            public int compare(Object o1, Object o2) {
                String so1 = (String) o1;
    String so2 = (String) o2;
    return so1.compareTo(so2);
    }
   }
  private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry");
  Collections.sort(VEGETABLES, new StringComparator());
  output: apple, blackberry, cocumbers
  

Elements sorting:

  private class Element implements Comparable {
               private String name;
               private Double atomicMass;
          
               @Override
                public String toString() {
                    final StringBuilder sb = new StringBuilder();
                    sb.append("Element");
                    sb.append("{name='").append(name).append('\'');
                    sb.append(", atomicMass=").append(atomicMass);
                    sb.append('}');
                    return sb.toString();
                }
          
                public String getName() {
                    return name;
                }
         
                public void setName(String name) {
                    this.name = name;
                }
         
                public Double getAtomicMass() {
                    return atomicMass;
                }
         
                public void setAtomicMass(Double atomicMass) {
                    this.atomicMass = atomicMass;
                }
        
                public Element(String name, String mass, double atomicMass) {
                    this.name = name;
                    this.atomicMass = atomicMass;
                }
        
                public int compareTo(Element o) {
                    return this.getAtomicMass().compareTo(o.getAtomicMass());
                }
            }
         
            ArrayList<Element> elements = new ArrayList<Element>();
            elements.add(new Element("Hydrogen", "H", 1.00794)); // Hydrogen 1.00794 amu Atomic Mass
            elements.add(new Element("Iron", "Fe", 55.845));
            elements.add(new Element("Lithium", "Li", 6.941));
            elements.add(new Element("Lead", "Pb", 207.2));
            elements.add(new Element("Magnesium", "Mg", 24.305));
            Collections.sort(elements);   // Sort by Element
            

output:

   Element{name='Hydrogen', atomicMass=1.00794}
            Element{name='Lithium', atomicMass=6.941}
            Element{name='Magnesium', atomicMass=24.305}
            Element{name='Iron', atomicMass=55.845}
            Element{name='Lead', atomicMass=207.2}
            

Chronological sorting:

  SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
        try {
   ArrayList<Date> holidays = new ArrayList<Date>();
            holidays.add(formatter.parse("May 31, 2010")); //  Memorial Day
            holidays.add(formatter.parse("July 4, 2010")); //  Independence Day
            holidays.add(formatter.parse("February 15, 2010")); //  Presidents Day
            holidays.add(formatter.parse("September 6, 2010")); // Labor Day
            holidays.add(formatter.parse("December 24, 2010")); // Thanksgiving Day
            holidays.add(formatter.parse("July 5, 2010")); //  federal employees extra day off for July 4th
            holidays.add(formatter.parse("January 18, 2010")); //  Martin Luther King Day
            holidays.add(formatter.parse("November 25, 2010")); // federal employees extra day off for Christmas
            holidays.add(formatter.parse("October 11, 2010")); // Columbus Day
            holidays.add(formatter.parse("December 25, 2010")); // Christmas Day
            holidays.add(formatter.parse("January 1, 2010")); // New Year's Day
            Collections.sort(holidays);  // Native sort for Date is chronological
           
            } catch (ParseException e) {
                e.printStackTrace();
            }
           

output:

     sorted:[Fri Jan 01 00:00:00 CET 2010, Mon Jan 18 00:00:00 CET 2010, Mon Feb 15 00:00:00 CET 2010, Mon May 31 00:00:00 CEST 2010, Sun Jul 04 00:00:00 CEST 2010, Mon Jul 05 00:00:00 CEST 2010, Mon Sep 06 00:00:00 CEST 2010, Mon Oct 11 00:00:00 CEST 2010, Thu Nov 25 00:00:00 CET 2010, Fri Dec 24 00:00:00 CET 2010, Sat Dec 25 00:00:00 CET 2010]
           

You can view the complete simple class below:

  
package com.tommyalf.personal.sorting;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* Created by IntelliJ IDEA.
* User: tommyalf
* Date: 1-dic-2010
* Time: 22.40.49
*/
public class SortDemo {
    private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry");;


    public static void main(String args[]) {
        SortDemo sd = new SortDemo();
        sd.normalSort();
        sd.reverseSort();
        sd.stringComparator();
        sd.elementsSort();
        sd.chronologicalSort();
    }

    private void chronologicalSort() {
        SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
        try {
            ArrayList<Date> holidays = new ArrayList<Date>();
            holidays.add(formatter.parse("May 31, 2010")); // Memorial Day
            holidays.add(formatter.parse("July 4, 2010")); // Independence Day
            holidays.add(formatter.parse("February 15, 2010")); // Presidents Day
            holidays.add(formatter.parse("September 6, 2010")); // Labor Day
            holidays.add(formatter.parse("December 24, 2010")); // Thanksgiving Day
            holidays.add(formatter.parse("July 5, 2010")); // federal employees extra day off for July 4th
            holidays.add(formatter.parse("January 18, 2010")); // Martin Luther King Day
            holidays.add(formatter.parse("November 25, 2010")); // federal employees extra day off for Christmas
            holidays.add(formatter.parse("October 11, 2010")); // Columbus Day
            holidays.add(formatter.parse("December 25, 2010")); // Christmas Day
            holidays.add(formatter.parse("January 1, 2010")); // New Year's Day
            System.out.println("before sort:" + holidays);
            Collections.sort(holidays); // Native sort for Date is chronological
            System.out.println("sorted:" + holidays);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void elementsSort() {
        ArrayList<Element> elements = new ArrayList<Element>();
        elements.add(new Element("Hydrogen", "H", 1.00794)); // Hydrogen 1.00794 amu Atomic Mass
        elements.add(new Element("Iron", "Fe", 55.845));
        elements.add(new Element("Lithium", "Li", 6.941));
        elements.add(new Element("Lead", "Pb", 207.2));
        elements.add(new Element("Magnesium", "Mg", 24.305));
        Collections.sort(elements); // Sort by Element
        System.out.print("Elements sort by atomicMass value:");
        for ( Element e : elements ) {
           System.out.println(e);
        }
    }

    private void stringComparator() {
        Collections.sort(VEGETABLES, new StringComparator());
        System.out.print("StringComparator:");
        printList(VEGETABLES);
    }

    private void reverseSort() {
        Collections.sort(VEGETABLES, Collections.reverseOrder());
        System.out.print("ReverseSort:");
        printList(VEGETABLES);
    }

    private void normalSort() {
        Collections.sort(VEGETABLES);
        System.out.print("NormalSort:");
        printList(VEGETABLES);
    }

    private void printList(List vegetables) {
        for (int i = 0, n = vegetables.size(); i < n; i++) {
            if (i != 0) {
                System.out.print(", ");
            }
            System.out.print(VEGETABLES.get(i));
        }
        System.out.println();
    }

    private class StringComparator implements Comparator {
        public int compare(Object o1, Object o2) {
            String so1 = (String) o1;
            String so2 = (String) o2;
            return so1.compareTo(so2);
        }
    }

    private class Element implements Comparable<Element> {
        private String name;
        private Double atomicMass;

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            sb.append("Element");
            sb.append("{name='").append(name).append('\'');
            sb.append(", atomicMass=").append(atomicMass);
            sb.append('}');
            return sb.toString();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Double getAtomicMass() {
            return atomicMass;
        }

        public void setAtomicMass(Double atomicMass) {
            this.atomicMass = atomicMass;
        }

        public Element(String name, String mass, double atomicMass) {
            this.name = name;
            this.atomicMass = atomicMass;
        }


        public int compareTo(Element o) {
            return this.getAtomicMass().compareTo(o.getAtomicMass());
        }
    }
}
  

Reference: Five useful ways to sorting in java from our JCG partner Tommy Alf at the Tommy Alf – blog blog.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button