Advertisement
NLinker

ValueComparator

Jul 8th, 2014
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.82 KB | None | 0 0
  1. public class Test {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         Map<Long,Double> map = new LinkedHashMap<Long, Double>();
  6.         map.put(1L, 3.0);
  7.         map.put(2L, 1.0);
  8.         map.put(3L, 4.0);
  9.         map.put(4L, 2.0);
  10.  
  11.         List<Map.Entry<Long, Double>> entriesOld = new ArrayList<Map.Entry<Long, Double>>(map.entrySet());
  12.         Collections.sort(entriesOld, new Old.ValueComparator());
  13.         // entriesOld = [3=4.0, 1=3.0, 4=2.0, 2=1.0]
  14.         System.out.println("entriesOld = " + entriesOld);
  15.  
  16.         List<Map.Entry<Long, Double>> entriesNew = new ArrayList<Map.Entry<Long, Double>>(map.entrySet());
  17.         Collections.sort(entriesNew, new New.ValueComparator());
  18.         // entriesNew = [3=4.0, 1=3.0, 4=2.0, 2=1.0]
  19.         System.out.println("entriesNew = " + entriesNew);
  20.  
  21.         Assert.assertEquals(entriesNew, entriesOld); // ok
  22.     }
  23.  
  24.     // Implementation before
  25.     public static class Old {
  26.         public static class ValueComparator implements Comparator{
  27.  
  28.             public ValueComparator() {
  29.             }
  30.  
  31.             public int compare(Object a, Object b) {
  32.                 if( (Double)(((Map.Entry)(a)).getValue()) < ((Double)((Map.Entry) (b)).getValue()) ) {
  33.                     return 1;
  34.                 } else if((Double)(((Map.Entry)(a)).getValue()) == (Double)(((Map.Entry)(b)).getValue())) {
  35.                     return 0;
  36.                 } else {
  37.                     return -1;
  38.                 }
  39.             }
  40.         }
  41.     }
  42.  
  43.     // Implementation after
  44.     public static class New {
  45.         public static class ValueComparator implements Comparator<Map.Entry<Long, Double>> {
  46.             public int compare(Map.Entry<Long, Double> a, Map.Entry<Long, Double> b) {
  47.                 return Double.compare(b.getValue(), a.getValue());
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement