tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > Google Guava > Collections > Multilevel Ordering

Multilevel Ordering 

Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using Ordering.from() and Ordering.compound() APIs. It allows us to perform multi level ordering.

File Name  :  
com/bethecoder/tutorials/guava/collection_tests/OrderingMultiLevelTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.guava.collection_tests;

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

import com.bethecoder.tutorials.guava.common.Bug;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;

public class OrderingMultiLevelTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    List<Bug> bugs = Lists.newArrayList(
      new Bug("Bug1""Open"3),
      new Bug("Bug2""Resolved"3),
      new Bug("Bug3""Closed"1),
      new Bug("Bug4""Open"4),
      new Bug("Bug5""Resolved"2),
      new Bug("Bug6""Open"1),
      new Bug("Bug7""Closed"3),
      new Bug("Bug8""Resolved"1)
    );
    
    Comparator<Bug> statusComp = new Comparator<Bug>() {
      @Override
      public int compare(Bug b1, Bug b2) {
        return b1.getStatus().compareToIgnoreCase(b2.getStatus());
      }
    };

    Comparator<Bug> priorityComp = new Comparator<Bug>() {
      @Override
      public int compare(Bug b1, Bug b2) {
        return Ints.compare(b1.getPriority(), b2.getPriority());
      }
    };
    
    System.out.println("Actual Bug List : ");
    showBugList(bugs);
    
    //Order by status and then priority
    List<Bug> sortedBugs = Ordering.from(statusComp).compound(priorityComp).sortedCopy(bugs);
    System.out.println("\nSorted Bug List : ");
    showBugList(sortedBugs);
  }

  private static void showBugList(List<Bug> bugs) {
    for (Bug bug : bugs) {
      System.out.println(bug);
    }
  }
}
   

It gives the following output,
Actual Bug List : 
Bug {Bug1, Open, 3]
Bug {Bug2, Resolved, 3]
Bug {Bug3, Closed, 1]
Bug {Bug4, Open, 4]
Bug {Bug5, Resolved, 2]
Bug {Bug6, Open, 1]
Bug {Bug7, Closed, 3]
Bug {Bug8, Resolved, 1]

Sorted Bug List : 
Bug {Bug3, Closed, 1]
Bug {Bug7, Closed, 3]
Bug {Bug6, Open, 1]
Bug {Bug1, Open, 3]
Bug {Bug4, Open, 4]
Bug {Bug8, Resolved, 1]
Bug {Bug5, Resolved, 2]
Bug {Bug2, Resolved, 3]



 
  


  
bl  br