|
| 1 | +package dev.Sorting; |
| 2 | + |
| 3 | +import org.junit.Before; |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +import java.sql.Array; |
| 7 | +import java.util.*; |
| 8 | + |
| 9 | +public class HashMapSortTest { |
| 10 | + |
| 11 | +// @Before |
| 12 | +// public void init(){ |
| 13 | +// |
| 14 | +// } |
| 15 | + |
| 16 | + |
| 17 | + @Test |
| 18 | + public void testSortMapWithValue(){ |
| 19 | + |
| 20 | + // ------------------- TEST 6 : sort map on val, key len |
| 21 | + Map<String, Integer> map = new HashMap<>(); |
| 22 | + map.put("apple", 3); |
| 23 | + map.put("banana", 2); |
| 24 | + map.put("lem", 3); |
| 25 | + map.put("kiwi", 5); |
| 26 | + map.put("peachhh", 3); |
| 27 | + |
| 28 | + System.out.println("Original map: " + map); |
| 29 | + |
| 30 | + /** |
| 31 | + * Note !!! |
| 32 | + * |
| 33 | + * difference between below: |
| 34 | + * |
| 35 | + * |
| 36 | + * 1) List<Set<String>> keys = Arrays.asList(map.keySet()); |
| 37 | + * In this line, you're using Arrays.asList() to wrap map.keySet() into a list. |
| 38 | + * map.keySet() returns a Set<String>, which is a set of the map's keys. |
| 39 | + * - Arrays.asList() takes an array (or a list of elements) |
| 40 | + * and converts it into a fixed-size list. When you pass a single Set to Arrays.asList(), |
| 41 | + * it wraps this single Set<String> into a list. |
| 42 | + * |
| 43 | + * 2) Arrays.asList() takes an array (or a list of elements) |
| 44 | + * and converts it into a fixed-size list. When you pass a single Set |
| 45 | + * to Arrays.asList(), it wraps this single Set<String> into a list. |
| 46 | + * -> So, keys will be a List<Set<String>> where the list contains a single Set<String>, which is the set of keys from the map. |
| 47 | + * |
| 48 | + */ |
| 49 | + //List<Set<String>> keys = Arrays.asList(map.keySet()); |
| 50 | + ArrayList<String> keyList = new ArrayList<>(map.keySet()); |
| 51 | + System.out.println(">>> (before sort) keyList = " + keyList); |
| 52 | + |
| 53 | + Collections.sort(keyList, (x,y) -> { |
| 54 | + // compare val, bigger first (decreasing order) |
| 55 | + int valDiff = map.get(y) - map.get(x); |
| 56 | + if (valDiff == 0){ |
| 57 | + // compare key len, shorter first (increasing order) |
| 58 | + return x.length() - y.length(); |
| 59 | + } |
| 60 | + return valDiff; |
| 61 | + }); |
| 62 | + |
| 63 | + System.out.println(">>> (after sort) keyList = " + keyList); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments