About Tommy Alf

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.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


3 × seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books