Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

7.2 a) Write a generic method public static <...> Collection<Pair<...>> sortPair

ID: 3763147 • Letter: 7

Question

 7.2 a) Write a generic method         public static <...> Collection<Pair<...>> sortPairCollection(Collection <Pair<....>> col)  in a Utils class that takes as parameter a collection of Pair<K,V> objects and returns a new collection object (use ArrayList<...>) with the pair elements from collection col sorted in ascending order. For comparing pairs, the K type must implement Comparable<....> Use the proper type constraints.  b)  Write a  main() function in Utils.java that tests the sortPairCollection() with K=String and V=Integer. 

Explanation / Answer

A)

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListSortingExample {

   private static class SmartPhone implements Comparable
     {
  
        private int price;

        public SmartPhone(int price)
        {
            this.price = price;
        }
    
        @Override
        public int compareTo(SmartPhone sp)
        {
            return this.brand.compareTo(sp.brand);
        }

        @Override
        public String toString()
        {
            return "SmartPhone{"price=" + price + '}';
        }
    
    }

    public static void main(String args)
    {
    
        //creating objects for arraylist sorting example
        SmartPhone apple = new SmartPhone(1000);
        SmartPhone nokia = new SmartPhone(600);
        SmartPhone samsung = new SmartPhone(800);
        SmartPhone lg = new SmartPhone(500);
    
        //creating Arraylist for sorting example
        ArrayList smartPhones = new ArrayList();
    
        //storing objects into ArrayList for sorting
        smartPhones.add(1000);
        smartPhones.add(600);
        smartPhones.add(800);
        smartPhones.add(500);
    
        //Sorting Arraylist in Java on natural order of object
        Collections.sort(smartPhones);
    
        //print sorted arraylist on natural order
        System.out.println(smartPhones);
    
        //Sorting Arraylist in Java on custom order defined by Comparator
        Collections.sort(smartPhones,new PriceComparator());
    
        //print sorted arraylist on custom order
        System.out.println(smartPhones);
  
    }
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote