Showing posts with label Find the Largest Number Using Comparator in Java. Show all posts
Showing posts with label Find the Largest Number Using Comparator in Java. Show all posts

Sunday, August 20, 2017

Find the Largest Number Using Comparator in Java

A program that I wrote that will arrange the given series of numbers and find the largest in terms of value using comparator library in Java. 

I hope you will find my work useful and beneficial. If you have some questions about programming, about my work please send mu an email at jakerpomperada@gmail.com and jakerpomperada@yahoo.com. People here in the Philippines can contact me at  my mobile number 09173084360.

Thank you very much and Happy Programming.



Program Sample Output


Program Listing

Solution.java

package exam;


import java.util.*;

public class Solution {
    private static Comparator<Integer> sorter = new Comparator<Integer>(){
        @Override
        public int compare(Integer a, Integer b){
            String a1 = a.toString();
            String b1 = b.toString();
            if(a1.length() == b1.length()){
                return b1.compareTo(a1);
            }
            int mlen = Math.max(a1.length(), b1.length());
            while(a1.length() < mlen * 2) a1 += a1;
            while(b1.length() < mlen * 2) b1 += b1;
            return b1.compareTo(b1);
        }
    };
    public static String join_all(List<?> things){
        String output = "";
        for(Object obj:things){
            output += obj;
        }
        return output;
    }
    public static void main(String[] args){
        List<Integer> num_values1 = new ArrayList<Integer>(Arrays.asList(2,1,3));
        List<Integer> num_values2 = new ArrayList<Integer>(Arrays.asList(1,4,7));
        List<Integer> num_values3 = new ArrayList<Integer>(Arrays.asList(4,8,3));
        List<Integer> num_values4 = new ArrayList<Integer>(Arrays.asList(4,6,3));
        
        System.out.println();
        System.out.print("Find the Largest Number Using Comparator in Java");
        System.out.println("\n\n");
        Collections.sort(num_values1, sorter);
        System.out.println(join_all(num_values1));
        
        System.out.println();
        Collections.sort(num_values2, sorter);
        System.out.println(join_all(num_values2));
        
        System.out.println();
        Collections.sort(num_values3, sorter);
        System.out.println(join_all(num_values3));
        
        System.out.println();
        Collections.sort(num_values4, sorter);
        System.out.println(join_all(num_values4));
        
    }
}