Compare two integers print value ascending or descending order
Below demo will show you how to compare two integers print value ascending or descending order . We will use Comparator interface to compare value and Collections class sort method to print value:
package com.javahonk.algorithms; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortingTest implements Comparator<Integer> { static Boolean ascending = false; public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(5); list.add(3); list.add(4); list.add(2); System.out.println("Unsorted list: " + list); // Sort list in descending order Collections.sort(list, new SortingTest()); System.out.println("\nSorted list descending order: " + list); //Sort list in ascending order: SortingTest.ascending = true; Collections.sort(list, new SortingTest()); System.out.println("\nSorted list ascending order: " + list); } @Override public int compare(Integer o1, Integer o2) { if (ascending) { return o1.intValue() - o2.intValue(); } else { return o2.intValue() - o1.intValue(); } } }
Output: