Guest User

Untitled

a guest
Nov 17th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.58 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class MapUtil {
  4. public static <K, V extends Comparable<? super V>> Map<K, V>
  5. sortByValue(Map<K, V> map) {
  6. List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
  7. Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
  8. public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
  9. return (o1.getValue()).compareTo( o2.getValue() );
  10. }
  11. });
  12.  
  13. Map<K, V> result = new LinkedHashMap<K, V>();
  14. for (Map.Entry<K, V> entry : list) {
  15. result.put(entry.getKey(), entry.getValue());
  16. }
  17. return result;
  18. }
  19. }
  20.  
  21. import java.util.*;
  22. import org.junit.*;
  23.  
  24. public class MapUtilTest {
  25. @Test
  26. public void testSortByValue() {
  27. Random random = new Random(System.currentTimeMillis());
  28. Map<String, Integer> testMap = new HashMap<String, Integer>(1000);
  29. for(int i = 0; i < 1000; ++i) {
  30. testMap.put( "SomeString" + random.nextInt(), random.nextInt());
  31. }
  32.  
  33. testMap = MapUtil.sortByValue(testMap);
  34. Assert.assertEquals(1000, testMap.size());
  35.  
  36. Integer previous = null;
  37. for(Map.Entry<String, Integer> entry : testMap.entrySet()) {
  38. Assert.assertNotNull(entry.getValue());
  39. if (previous != null) {
  40. Assert.assertTrue(entry.getValue() >= previous);
  41. }
  42. previous = entry.getValue();
  43. }
  44. }
  45. }
  46.  
  47. public static <K, V extends Comparable<? super V>> Map<K, V>
  48. sortByValue(Map<K, V> map) {
  49. List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
  50. Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
  51. @Override
  52. public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
  53. return (o1.getValue()).compareTo(o2.getValue());
  54. }
  55. });
  56.  
  57. Map<K, V> result = new LinkedHashMap<>();
  58. for (Map.Entry<K, V> entry : list) {
  59. result.put(entry.getKey(), entry.getValue());
  60. }
  61. return result;
  62. }
  63.  
  64. public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
  65. return map.entrySet()
  66. .stream()
  67. .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
  68. .collect(Collectors.toMap(
  69. Map.Entry::getKey,
  70. Map.Entry::getValue,
  71. (e1, e2) -> e1,
  72. LinkedHashMap::new
  73. ));
  74. }
  75.  
  76. private static LinkedHashMap<String, String> method1(HashMap<String, String> originalHashMap) {
  77. LinkedHashMap<String, String> sortedHashMapByKeys = new LinkedHashMap<>(); //maintains the order of putting
  78. TreeMap<String, String> originalTreeMap = new TreeMap<>(originalHashMap); //sorts based on keys
  79. for (Map.Entry<String, String> map: originalTreeMap.entrySet()) {
  80. sortedHashMapByKeys.put(map.getKey(), map.getValue());
  81. }
  82.  
  83. LinkedHashMap<String, String> reversedOfSortedLinkedHashMap = new LinkedHashMap<>();
  84. for (Map.Entry<String, String> map: sortedHashMapByKeys.entrySet()) {
  85. reversedOfSortedLinkedHashMap.put(map.getValue(), map.getKey());
  86. }
  87.  
  88. LinkedHashMap<String, String> finalMap = new LinkedHashMap<>();
  89. TreeMap<String, String> treeMapOfReversedOfSortedLinkedHashMap = new TreeMap<>(reversedOfSortedLinkedHashMap);
  90. for (Map.Entry<String, String> map: treeMapOfReversedOfSortedLinkedHashMap.entrySet()) {
  91. finalMap.put(map.getKey(), map.getValue()); //sort and swap
  92. }
  93. return finalMap;
  94. }
  95.  
  96. public class Testing {
  97. public static void main(String[] args) {
  98. HashMap<String, Double> map = new HashMap<String, Double>();
  99. ValueComparator bvc = new ValueComparator(map);
  100. TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);
  101.  
  102. map.put("A", 99.5);
  103. map.put("B", 67.4);
  104. map.put("C", 67.4);
  105. map.put("D", 67.3);
  106.  
  107. System.out.println("unsorted map: " + map);
  108. sorted_map.putAll(map);
  109. System.out.println("results: " + sorted_map);
  110. }
  111. }
  112.  
  113. class ValueComparator implements Comparator<String> {
  114. Map<String, Double> base;
  115.  
  116. public ValueComparator(Map<String, Double> base) {
  117. this.base = base;
  118. }
  119.  
  120. // Note: this comparator imposes orderings that are inconsistent with
  121. // equals.
  122. public int compare(String a, String b) {
  123. if (base.get(a) >= base.get(b)) {
  124. return -1;
  125. } else {
  126. return 1;
  127. } // returning 0 would merge keys
  128. }
  129. }
  130.  
  131. unsorted map: {D=67.3, A=99.5, B=67.4, C=67.4}
  132. results: {D=67.3, B=67.4, C=67.4, A=99.5}
  133.  
  134. valueComparator = Ordering.natural().onResultOf(Functions.forMap(map))
  135.  
  136. valueComparator = Ordering.from(comparator).onResultOf(Functions.forMap(map))
  137.  
  138. valueComparator = Ordering.natural().onResultOf(Functions.forMap(map)).compound(Ordering.natural())
  139.  
  140. map = ImmutableSortedMap.copyOf(myOriginalMap, valueComparator);
  141.  
  142. import static org.junit.Assert.assertEquals;
  143.  
  144. import java.util.HashMap;
  145. import java.util.Map;
  146. import java.util.TreeMap;
  147.  
  148. import com.google.common.base.Functions;
  149. import com.google.common.collect.Ordering;
  150.  
  151. class ValueComparableMap<K extends Comparable<K>,V> extends TreeMap<K,V> {
  152. //A map for doing lookups on the keys for comparison so we don't get infinite loops
  153. private final Map<K, V> valueMap;
  154.  
  155. ValueComparableMap(final Ordering<? super V> partialValueOrdering) {
  156. this(partialValueOrdering, new HashMap<K,V>());
  157. }
  158.  
  159. private ValueComparableMap(Ordering<? super V> partialValueOrdering,
  160. HashMap<K, V> valueMap) {
  161. super(partialValueOrdering //Apply the value ordering
  162. .onResultOf(Functions.forMap(valueMap)) //On the result of getting the value for the key from the map
  163. .compound(Ordering.natural())); //as well as ensuring that the keys don't get clobbered
  164. this.valueMap = valueMap;
  165. }
  166.  
  167. public V put(K k, V v) {
  168. if (valueMap.containsKey(k)){
  169. //remove the key in the sorted set before adding the key again
  170. remove(k);
  171. }
  172. valueMap.put(k,v); //To get "real" unsorted values for the comparator
  173. return super.put(k, v); //Put it in value order
  174. }
  175.  
  176. public static void main(String[] args){
  177. TreeMap<String, Integer> map = new ValueComparableMap<String, Integer>(Ordering.natural());
  178. map.put("a", 5);
  179. map.put("b", 1);
  180. map.put("c", 3);
  181. assertEquals("b",map.firstKey());
  182. assertEquals("a",map.lastKey());
  183. map.put("d",0);
  184. assertEquals("d",map.firstKey());
  185. //ensure it's still a map (by overwriting a key, but with a new value)
  186. map.put("d", 2);
  187. assertEquals("b", map.firstKey());
  188. //Ensure multiple values do not clobber keys
  189. map.put("e", 2);
  190. assertEquals(5, map.size());
  191. assertEquals(2, (int) map.get("e"));
  192. assertEquals(2, (int) map.get("d"));
  193. }
  194. }
  195.  
  196. new ValueComparableMap(Ordering.natural());
  197. //or
  198. new ValueComparableMap(Ordering.from(comparator));
  199.  
  200. private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
  201. List<Entry<K, V>> list = new LinkedList<>(map.entrySet());
  202. Collections.sort(list, new Comparator<Object>() {
  203. @SuppressWarnings("unchecked")
  204. public int compare(Object o1, Object o2) {
  205. return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
  206. }
  207. });
  208.  
  209. Map<K, V> result = new LinkedHashMap<>();
  210. for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {
  211. Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
  212. result.put(entry.getKey(), entry.getValue());
  213. }
  214.  
  215. return result;
  216. }
  217.  
  218. Stream<Map.Entry<K,V>> sorted =
  219. map.entrySet().stream()
  220. .sorted(Map.Entry.comparingByValue());
  221.  
  222. Stream<Map.Entry<K,V>> sorted =
  223. map.entrySet().stream()
  224. .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
  225.  
  226. Stream<Map.Entry<K,V>> sorted =
  227. map.entrySet().stream()
  228. .sorted(Map.Entry.comparingByValue(comparator));
  229.  
  230. Map<K,V> topTen =
  231. map.entrySet().stream()
  232. .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
  233. .limit(10)
  234. .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  235.  
  236. map.entrySet().stream()
  237. .sorted(Map.Entry.comparingByValue())
  238. .forEach(System.out::println);
  239.  
  240. public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue(Map<K, V> map) {
  241. final int size = map.size();
  242. final List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size);
  243. list.addAll(map.entrySet());
  244. final ValueComparator<V> cmp = new ValueComparator<V>();
  245. Collections.sort(list, cmp);
  246. final List<K> keys = new ArrayList<K>(size);
  247. for (int i = 0; i < size; i++) {
  248. keys.set(i, list.get(i).getKey());
  249. }
  250. return keys;
  251. }
  252.  
  253. private static final class ValueComparator<V extends Comparable<? super V>>
  254. implements Comparator<Map.Entry<?, V>> {
  255. public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {
  256. return o1.getValue().compareTo(o2.getValue());
  257. }
  258. }
  259.  
  260. public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue2(Map<K, V> map) {
  261. final int size = map.size();
  262. final List reusedList = new ArrayList(size);
  263. final List<Map.Entry<K, V>> meView = reusedList;
  264. meView.addAll(map.entrySet());
  265. Collections.sort(meView, SINGLE);
  266. final List<K> keyView = reusedList;
  267. for (int i = 0; i < size; i++) {
  268. keyView.set(i, meView.get(i).getKey());
  269. }
  270. return keyView;
  271. }
  272.  
  273. private static final Comparator SINGLE = new ValueComparator();
  274.  
  275. Map<K, V> sortedMap = map.entrySet().stream()
  276. .sorted(Entry.comparingByValue())
  277. .collect(toMap(Entry::getKey, Entry::getValue,
  278. (e1,e2) -> e1, LinkedHashMap::new));
  279.  
  280. public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
  281. Comparator<K> valueComparator = new Comparator<K>() {
  282. public int compare(K k1, K k2) {
  283. int compare = map.get(k2).compareTo(map.get(k1));
  284. if (compare == 0) return 1;
  285. else return compare;
  286. }
  287. };
  288. Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
  289. sortedByValues.putAll(map);
  290. return sortedByValues;
  291. }
  292.  
  293. import static java.util.Map.Entry.comparingByValue;
  294. import static java.util.stream.Collectors.toList;
  295.  
  296. <K, V> List<Entry<K, V>> sort(Map<K, V> map, Comparator<? super V> comparator) {
  297. return map.entrySet().stream().sorted(comparingByValue(comparator)).collect(toList());
  298. }
  299.  
  300. <K, V extends Comparable<? super V>> List<Entry<K, V>> sort(Map<K, V> map) {
  301. return map.entrySet().stream().sorted(comparingByValue()).collect(toList());
  302. }
  303.  
  304. <K, V extends Comparable<? super V>> Iterable<Entry<K, V>> sort(Map<K, V> map) {
  305. return () -> map.entrySet().stream().sorted(comparingByValue()).iterator();
  306. }
  307.  
  308. class MyComparator implements Comparator<Object> {
  309.  
  310. Map<String, Integer> map;
  311.  
  312. public MyComparator(Map<String, Integer> map) {
  313. this.map = map;
  314. }
  315.  
  316. public int compare(Object o1, Object o2) {
  317.  
  318. if (map.get(o2) == map.get(o1))
  319. return 1;
  320. else
  321. return ((Integer) map.get(o2)).compareTo((Integer)
  322. map.get(o1));
  323.  
  324. }
  325. }
  326.  
  327. Map<String, Integer> lMap = new HashMap<String, Integer>();
  328. lMap.put("A", 35);
  329. lMap.put("B", 75);
  330. lMap.put("C", 50);
  331. lMap.put("D", 50);
  332.  
  333. MyComparator comparator = new MyComparator(lMap);
  334.  
  335. Map<String, Integer> newMap = new TreeMap<String, Integer>(comparator);
  336. newMap.putAll(lMap);
  337. System.out.println(newMap);
  338.  
  339. {B=75, D=50, C=50, A=35}
  340.  
  341. public class MapUtilities {
  342.  
  343. public static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValue(Map<K, V> map) {
  344. List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(map.entrySet());
  345. Collections.sort(entries, new ByValue<K, V>());
  346. return entries;
  347. }
  348.  
  349. private static class ByValue<K, V extends Comparable<V>> implements Comparator<Entry<K, V>> {
  350. public int compare(Entry<K, V> o1, Entry<K, V> o2) {
  351. return o1.getValue().compareTo(o2.getValue());
  352. }
  353. }
  354.  
  355. public class MapUtilitiesTest extends TestCase {
  356. public void testSorting() {
  357. HashMap<String, Integer> map = new HashMap<String, Integer>();
  358. map.put("One", 1);
  359. map.put("Two", 2);
  360. map.put("Three", 3);
  361.  
  362. List<Map.Entry<String, Integer>> sorted = MapUtilities.sortByValue(map);
  363. assertEquals("First", "One", sorted.get(0).getKey());
  364. assertEquals("Second", "Two", sorted.get(1).getKey());
  365. assertEquals("Third", "Three", sorted.get(2).getKey());
  366. }
  367.  
  368. final class MapValueComparator<K,V extends Comparable<V>> implements Comparator<K> {
  369.  
  370. private Map<K,V> map;
  371.  
  372. private MapValueComparator() {
  373. super();
  374. }
  375.  
  376. public MapValueComparator(Map<K,V> map) {
  377. this();
  378. this.map = map;
  379. }
  380.  
  381. public int compare(K o1, K o2) {
  382. return map.get(o1).compareTo(map.get(o2));
  383. }
  384. }
  385.  
  386. if((Double)base.get(a) < (Double)base.get(b)) {
  387. return 1;
  388. } else if((Double)base.get(a) == (Double)base.get(b)) {
  389. return -1;
  390. } else {
  391. return -1;
  392. }
  393.  
  394. if((Double)base.get(a) < (Double)base.get(b)) {
  395. return 1;
  396. } else if((Double)base.get(a) == (Double)base.get(b)) {
  397. return -1;
  398. } else {
  399. return -1;
  400. }
  401.  
  402. if((Double)base.get(a) < (Double)base.get(b)) {
  403. return 1;
  404. } else if((Double)base.get(a) == (Double)base.get(b)) {
  405. return -1;
  406. } else {
  407. return -1;
  408. }
  409.  
  410. package nl.iamit.util;
  411.  
  412. import java.util.Comparator;
  413. import java.util.Map;
  414.  
  415. public class Comparators {
  416.  
  417.  
  418. public static class MapIntegerStringComparator implements Comparator {
  419.  
  420. Map<Integer, String> base;
  421.  
  422. public MapIntegerStringComparator(Map<Integer, String> base) {
  423. this.base = base;
  424. }
  425.  
  426. public int compare(Object a, Object b) {
  427.  
  428. int compare = ((String) base.get(a))
  429. .compareTo((String) base.get(b));
  430. if (compare == 0) {
  431. return -1;
  432. }
  433. return compare;
  434. }
  435. }
  436.  
  437.  
  438. }
  439.  
  440. package nl.iamit.util;
  441.  
  442. import java.util.Comparator;
  443. import java.util.Map;
  444.  
  445. public class Comparators {
  446.  
  447.  
  448. public static class MapIntegerStringComparator implements Comparator {
  449.  
  450. Map<Integer, String> base;
  451.  
  452. public MapIntegerStringComparator(Map<Integer, String> base) {
  453. this.base = base;
  454. }
  455.  
  456. public int compare(Object a, Object b) {
  457.  
  458. int compare = ((String) base.get(a))
  459. .compareTo((String) base.get(b));
  460. if (compare == 0) {
  461. return -1;
  462. }
  463. return compare;
  464. }
  465. }
  466.  
  467.  
  468. }
  469.  
  470. package nl.iamit.util;
  471.  
  472. import java.util.Comparator;
  473. import java.util.Map;
  474.  
  475. public class Comparators {
  476.  
  477.  
  478. public static class MapIntegerStringComparator implements Comparator {
  479.  
  480. Map<Integer, String> base;
  481.  
  482. public MapIntegerStringComparator(Map<Integer, String> base) {
  483. this.base = base;
  484. }
  485.  
  486. public int compare(Object a, Object b) {
  487.  
  488. int compare = ((String) base.get(a))
  489. .compareTo((String) base.get(b));
  490. if (compare == 0) {
  491. return -1;
  492. }
  493. return compare;
  494. }
  495. }
  496.  
  497.  
  498. }
  499.  
  500. package test.nl.iamit.util;
  501.  
  502. import java.util.HashMap;
  503. import java.util.TreeMap;
  504. import nl.iamit.util.Comparators;
  505. import org.junit.Test;
  506. import static org.junit.Assert.assertArrayEquals;
  507.  
  508. public class TestComparators {
  509.  
  510.  
  511. @Test
  512. public void testMapIntegerStringComparator(){
  513. HashMap<Integer, String> unSoretedMap = new HashMap<Integer, String>();
  514. Comparators.MapIntegerStringComparator bvc = new Comparators.MapIntegerStringComparator(
  515. unSoretedMap);
  516. TreeMap<Integer, String> sorted_map = new TreeMap<Integer, String>(bvc);
  517. //the testdata:
  518. unSoretedMap.put(new Integer(1), "E");
  519. unSoretedMap.put(new Integer(2), "A");
  520. unSoretedMap.put(new Integer(3), "E");
  521. unSoretedMap.put(new Integer(4), "B");
  522. unSoretedMap.put(new Integer(5), "F");
  523.  
  524. sorted_map.putAll(unSoretedMap);
  525.  
  526. Object[] targetKeys={new Integer(2),new Integer(4),new Integer(3),new Integer(1),new Integer(5) };
  527. Object[] currecntKeys=sorted_map.keySet().toArray();
  528.  
  529. assertArrayEquals(targetKeys,currecntKeys);
  530. }
  531. }
  532.  
  533. public static class MapStringDoubleComparator implements Comparator {
  534.  
  535. Map<String, Double> base;
  536.  
  537. public MapStringDoubleComparator(Map<String, Double> base) {
  538. this.base = base;
  539. }
  540.  
  541. //note if you want decending in stead of ascending, turn around 1 and -1
  542. public int compare(Object a, Object b) {
  543. if ((Double) base.get(a) == (Double) base.get(b)) {
  544. return 0;
  545. } else if((Double) base.get(a) < (Double) base.get(b)) {
  546. return -1;
  547. }else{
  548. return 1;
  549. }
  550. }
  551. }
  552.  
  553. @Test
  554. public void testMapStringDoubleComparator(){
  555. HashMap<String, Double> unSoretedMap = new HashMap<String, Double>();
  556. Comparators.MapStringDoubleComparator bvc = new Comparators.MapStringDoubleComparator(
  557. unSoretedMap);
  558. TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);
  559. //the testdata:
  560. unSoretedMap.put("D",new Double(67.3));
  561. unSoretedMap.put("A",new Double(99.5));
  562. unSoretedMap.put("B",new Double(67.4));
  563. unSoretedMap.put("C",new Double(67.5));
  564. unSoretedMap.put("E",new Double(99.5));
  565.  
  566. sorted_map.putAll(unSoretedMap);
  567.  
  568. Object[] targetKeys={"D","B","C","E","A"};
  569. Object[] currecntKeys=sorted_map.keySet().toArray();
  570.  
  571. assertArrayEquals(targetKeys,currecntKeys);
  572. }
  573.  
  574. public static <T extends Comparable<? super T>> void sort(List<T> list) {
  575. Object[] a = list.toArray();
  576. Arrays.sort(a);
  577. ListIterator<T> i = list.listIterator();
  578. for (int j=0; j<a.length; j++) {
  579. i.next();
  580. i.set((T)a[j]);
  581. }
  582. }
  583.  
  584. public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map)
  585. {
  586. @SuppressWarnings("unchecked")
  587. Map.Entry<K,V>[] array = map.entrySet().toArray(new Map.Entry[map.size()]);
  588.  
  589. Arrays.sort(array, new Comparator<Map.Entry<K, V>>()
  590. {
  591. public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2)
  592. {
  593. return e1.getValue().compareTo(e2.getValue());
  594. }
  595. });
  596.  
  597. Map<K, V> result = new LinkedHashMap<K, V>();
  598. for (Map.Entry<K, V> entry : array)
  599. result.put(entry.getKey(), entry.getValue());
  600.  
  601. return result;
  602. }
  603.  
  604. public static <K, V extends Comparable<V>> Map<K, V> sortMapByValues(final Map<K, V> map) {
  605. Comparator<K> valueComparator = new Comparator<K>() {
  606. public int compare(K k1, K k2) {
  607. final V v1 = map.get(k1);
  608. final V v2 = map.get(k2);
  609.  
  610. /* Not sure how to handle nulls ... */
  611. if (v1 == null) {
  612. return (v2 == null) ? 0 : 1;
  613. }
  614.  
  615. int compare = v2.compareTo(v1);
  616. if (compare != 0)
  617. {
  618. return compare;
  619. }
  620. else
  621. {
  622. Integer h1 = k1.hashCode();
  623. Integer h2 = k2.hashCode();
  624. return h2.compareTo(h1);
  625. }
  626. }
  627. };
  628. Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
  629. sortedByValues.putAll(map);
  630. return sortedByValues;
  631. }
  632.  
  633. public int compare(String a, String b) {
  634. if (base.get(a) > base.get(b)) {
  635. return 1;
  636. } else if (base.get(a) < base.get(b)){
  637. return -1;
  638. }
  639.  
  640. return 0;
  641. // returning 0 would merge keys
  642. }
  643.  
  644. import java.util.*;
  645.  
  646. /**
  647. * A map where {@link #keySet()} and {@link #entrySet()} return sets ordered
  648. * by associated values based on the the comparator provided at construction
  649. * time. The order of two or more keys with identical values is not defined.
  650. * <p>
  651. * Several contracts of the Map interface are not satisfied by this minimal
  652. * implementation.
  653. */
  654. public class ValueSortedMap<K, V> extends HashMap<K, V> {
  655. protected Map<V, Collection<K>> valueToKeysMap;
  656.  
  657. // uses natural order of value object, if any
  658. public ValueSortedMap() {
  659. this((Comparator<? super V>) null);
  660. }
  661.  
  662. public ValueSortedMap(Comparator<? super V> valueComparator) {
  663. this.valueToKeysMap = new TreeMap<V, Collection<K>>(valueComparator);
  664. }
  665.  
  666. public boolean containsValue(Object o) {
  667. return valueToKeysMap.containsKey(o);
  668. }
  669.  
  670. public V put(K k, V v) {
  671. V oldV = null;
  672. if (containsKey(k)) {
  673. oldV = get(k);
  674. valueToKeysMap.get(oldV).remove(k);
  675. }
  676. super.put(k, v);
  677. if (!valueToKeysMap.containsKey(v)) {
  678. Collection<K> keys = new ArrayList<K>();
  679. keys.add(k);
  680. valueToKeysMap.put(v, keys);
  681. } else {
  682. valueToKeysMap.get(v).add(k);
  683. }
  684. return oldV;
  685. }
  686.  
  687. public void putAll(Map<? extends K, ? extends V> m) {
  688. for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
  689. put(e.getKey(), e.getValue());
  690. }
  691.  
  692. public V remove(Object k) {
  693. V oldV = null;
  694. if (containsKey(k)) {
  695. oldV = get(k);
  696. super.remove(k);
  697. valueToKeysMap.get(oldV).remove(k);
  698. }
  699. return oldV;
  700. }
  701.  
  702. public void clear() {
  703. super.clear();
  704. valueToKeysMap.clear();
  705. }
  706.  
  707. public Set<K> keySet() {
  708. LinkedHashSet<K> ret = new LinkedHashSet<K>(size());
  709. for (V v : valueToKeysMap.keySet()) {
  710. Collection<K> keys = valueToKeysMap.get(v);
  711. ret.addAll(keys);
  712. }
  713. return ret;
  714. }
  715.  
  716. public Set<Map.Entry<K, V>> entrySet() {
  717. LinkedHashSet<Map.Entry<K, V>> ret = new LinkedHashSet<Map.Entry<K, V>>(size());
  718. for (Collection<K> keys : valueToKeysMap.values()) {
  719. for (final K k : keys) {
  720. final V v = get(k);
  721. ret.add(new Map.Entry<K,V>() {
  722. public K getKey() {
  723. return k;
  724. }
  725.  
  726. public V getValue() {
  727. return v;
  728. }
  729.  
  730. public V setValue(V v) {
  731. throw new UnsupportedOperationException();
  732. }
  733. });
  734. }
  735. }
  736. return ret;
  737. }
  738. }
  739.  
  740. Map<Driver driver, Float time> map = new TreeMap<Driver driver, Float time>(*);
  741.  
  742. ResultComparator rc = new ResultComparator();
  743. Set<Results> set = new TreeSet<Results>(rc);
  744.  
  745. public class Results {
  746. private Driver driver;
  747. private Float time;
  748.  
  749. public Results(Driver driver, Float time) {
  750. this.driver = driver;
  751. this.time = time;
  752. }
  753.  
  754. public Float getTime() {
  755. return time;
  756. }
  757.  
  758. public void setTime(Float time) {
  759. this.time = time;
  760. }
  761.  
  762. public Driver getDriver() {
  763. return driver;
  764. }
  765.  
  766. public void setDriver (Driver driver) {
  767. this.driver = driver;
  768. }
  769. }
  770.  
  771. public class ResultsComparator implements Comparator<Results> {
  772. public int compare(Results t, Results t1) {
  773. if (t.getTime() < t1.getTime()) {
  774. return 1;
  775. } else if (t.getTime() == t1.getTime()) {
  776. return 0;
  777. } else {
  778. return -1;
  779. }
  780. }
  781. }
  782.  
  783. Iterator it = set.iterator();
  784. while (it.hasNext()) {
  785. Results r = (Results)it.next();
  786. System.out.println( r.getDriver().toString
  787. //or whatever that is related to Driver class -getName() getSurname()
  788. + " "
  789. + r.getTime()
  790. );
  791. }
  792.  
  793. import java.util.ArrayList;
  794. import java.util.Collections;
  795. import java.util.Comparator;
  796. import java.util.HashMap;
  797. import java.util.List;
  798. import java.util.Map;
  799. import java.util.Set;
  800. import java.util.Map.Entry;
  801.  
  802. public class OrderByValue {
  803.  
  804. public static void main(String a[]){
  805. Map<String, Integer> map = new HashMap<String, Integer>();
  806. map.put("java", 20);
  807. map.put("C++", 45);
  808. map.put("Unix", 67);
  809. map.put("MAC", 26);
  810. map.put("Why this kolavari", 93);
  811. Set<Entry<String, Integer>> set = map.entrySet();
  812. List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
  813. Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
  814. {
  815. public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
  816. {
  817. return (o1.getValue()).compareTo( o2.getValue() );//Ascending order
  818. //return (o2.getValue()).compareTo( o1.getValue() );//Descending order
  819. }
  820. } );
  821. for(Map.Entry<String, Integer> entry:list){
  822. System.out.println(entry.getKey()+" ==== "+entry.getValue());
  823. }
  824. }}
  825.  
  826. java ==== 20
  827.  
  828. MAC ==== 26
  829.  
  830. C++ ==== 45
  831.  
  832. Unix ==== 67
  833.  
  834. Why this kolavari ==== 93
  835.  
  836. /**
  837. * Sort a map by it's keys in ascending order.
  838. *
  839. * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.
  840. * @author Maxim Veksler
  841. */
  842. public static <K, V> LinkedHashMap<K, V> sortMapByKey(final Map<K, V> map) {
  843. return sortMapByKey(map, SortingOrder.ASCENDING);
  844. }
  845.  
  846. /**
  847. * Sort a map by it's values in ascending order.
  848. *
  849. * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.
  850. * @author Maxim Veksler
  851. */
  852. public static <K, V> LinkedHashMap<K, V> sortMapByValue(final Map<K, V> map) {
  853. return sortMapByValue(map, SortingOrder.ASCENDING);
  854. }
  855.  
  856. /**
  857. * Sort a map by it's keys.
  858. *
  859. * @param sortingOrder {@link SortingOrder} enum specifying requested sorting order.
  860. * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.
  861. * @author Maxim Veksler
  862. */
  863. public static <K, V> LinkedHashMap<K, V> sortMapByKey(final Map<K, V> map, final SortingOrder sortingOrder) {
  864. Comparator<Map.Entry<K, V>> comparator = new Comparator<Entry<K,V>>() {
  865. public int compare(Entry<K, V> o1, Entry<K, V> o2) {
  866. return comparableCompare(o1.getKey(), o2.getKey(), sortingOrder);
  867. }
  868. };
  869.  
  870. return sortMap(map, comparator);
  871. }
  872.  
  873. /**
  874. * Sort a map by it's values.
  875. *
  876. * @param sortingOrder {@link SortingOrder} enum specifying requested sorting order.
  877. * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.
  878. * @author Maxim Veksler
  879. */
  880. public static <K, V> LinkedHashMap<K, V> sortMapByValue(final Map<K, V> map, final SortingOrder sortingOrder) {
  881. Comparator<Map.Entry<K, V>> comparator = new Comparator<Entry<K,V>>() {
  882. public int compare(Entry<K, V> o1, Entry<K, V> o2) {
  883. return comparableCompare(o1.getValue(), o2.getValue(), sortingOrder);
  884. }
  885. };
  886.  
  887. return sortMap(map, comparator);
  888. }
  889.  
  890. @SuppressWarnings("unchecked")
  891. private static <T> int comparableCompare(T o1, T o2, SortingOrder sortingOrder) {
  892. int compare = ((Comparable<T>)o1).compareTo(o2);
  893.  
  894. switch (sortingOrder) {
  895. case ASCENDING:
  896. return compare;
  897. case DESCENDING:
  898. return (-1) * compare;
  899. }
  900.  
  901. return 0;
  902. }
  903.  
  904. /**
  905. * Sort a map by supplied comparator logic.
  906. *
  907. * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.
  908. * @author Maxim Veksler
  909. */
  910. public static <K, V> LinkedHashMap<K, V> sortMap(final Map<K, V> map, final Comparator<Map.Entry<K, V>> comparator) {
  911. // Convert the map into a list of key,value pairs.
  912. List<Map.Entry<K, V>> mapEntries = new LinkedList<Map.Entry<K, V>>(map.entrySet());
  913.  
  914. // Sort the converted list according to supplied comparator.
  915. Collections.sort(mapEntries, comparator);
  916.  
  917. // Build a new ordered map, containing the same entries as the old map.
  918. LinkedHashMap<K, V> result = new LinkedHashMap<K, V>(map.size() + (map.size() / 20));
  919. for(Map.Entry<K, V> entry : mapEntries) {
  920. // We iterate on the mapEntries list which is sorted by the comparator putting new entries into
  921. // the targeted result which is a sorted map.
  922. result.put(entry.getKey(), entry.getValue());
  923. }
  924.  
  925. return result;
  926. }
  927.  
  928. /**
  929. * Sorting order enum, specifying request result sort behavior.
  930. * @author Maxim Veksler
  931. *
  932. */
  933. public static enum SortingOrder {
  934. /**
  935. * Resulting sort will be from smaller to biggest.
  936. */
  937. ASCENDING,
  938. /**
  939. * Resulting sort will be from biggest to smallest.
  940. */
  941. DESCENDING
  942. }
  943.  
  944. import java.util.Collections;
  945. import java.util.Comparator;
  946. import java.util.HashMap;
  947. import java.util.Iterator;
  948. import java.util.LinkedList;
  949. import java.util.LinkedHashMap;
  950. import java.util.List;
  951. import java.util.Map;
  952.  
  953. public class SortableValueMap<K, V extends Comparable<V>>
  954. extends LinkedHashMap<K, V> {
  955. public SortableValueMap() { }
  956.  
  957. public SortableValueMap( Map<K, V> map ) {
  958. super( map );
  959. }
  960.  
  961. public void sortByValue() {
  962. List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( entrySet() );
  963.  
  964. Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
  965. public int compare( Map.Entry<K, V> entry1, Map.Entry<K, V> entry2 ) {
  966. return entry1.getValue().compareTo( entry2.getValue() );
  967. }
  968. });
  969.  
  970. clear();
  971.  
  972. for( Map.Entry<K, V> entry : list ) {
  973. put( entry.getKey(), entry.getValue() );
  974. }
  975. }
  976.  
  977. private static void print( String text, Map<String, Double> map ) {
  978. System.out.println( text );
  979.  
  980. for( String key : map.keySet() ) {
  981. System.out.println( "key/value: " + key + "/" + map.get( key ) );
  982. }
  983. }
  984.  
  985. public static void main( String[] args ) {
  986. SortableValueMap<String, Double> map =
  987. new SortableValueMap<String, Double>();
  988.  
  989. map.put( "A", 67.5 );
  990. map.put( "B", 99.5 );
  991. map.put( "C", 82.4 );
  992. map.put( "D", 42.0 );
  993.  
  994. print( "Unsorted map", map );
  995. map.sortByValue();
  996. print( "Sorted map", map );
  997. }
  998. }
  999.  
  1000. Map<String, Long> map = new HashMap<String, Long>();
  1001. // populate with data to sort on Value
  1002. // use datastructure designed for sorting
  1003.  
  1004. Queue queue = new PriorityQueue( map.size(), new MapComparable() );
  1005. queue.addAll( map.entrySet() );
  1006.  
  1007. // get a sorted map
  1008. LinkedHashMap<String, Long> linkedMap = new LinkedHashMap<String, Long>();
  1009.  
  1010. for (Map.Entry<String, Long> entry; (entry = queue.poll())!=null;) {
  1011. linkedMap.put(entry.getKey(), entry.getValue());
  1012. }
  1013.  
  1014. public static class MapComparable implements Comparator<Map.Entry<String, Long>>{
  1015.  
  1016. public int compare(Entry<String, Long> e1, Entry<String, Long> e2) {
  1017. return e1.getValue().compareTo(e2.getValue());
  1018. }
  1019. }
  1020.  
  1021. private <K, V extends Comparable<? super V>> List<Entry<K, V>> sort(Map<K, V> map) {
  1022. List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
  1023. Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
  1024. public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
  1025. return o1.getValue().compareTo(o2.getValue());
  1026. }
  1027. });
  1028.  
  1029. return list;
  1030. }
  1031.  
  1032. public int compare(Object a, Object b) {
  1033.  
  1034. if((Double)base.get(a) < (Double)base.get(b)) {
  1035. return 1;
  1036. } else if((Double)base.get(a) == (Double)base.get(b)) {
  1037. return ((String)a).compareTo((String)b);
  1038. } else {
  1039. return -1;
  1040. }
  1041. }
  1042. }
  1043.  
  1044. // If you want to sort a map by value, and if there can be twice the same value:
  1045.  
  1046. // here is your original map
  1047. Map<String,Integer> mapToSortByValue = new HashMap<String, Integer>();
  1048. mapToSortByValue.put("A", 3);
  1049. mapToSortByValue.put("B", 1);
  1050. mapToSortByValue.put("C", 3);
  1051. mapToSortByValue.put("D", 5);
  1052. mapToSortByValue.put("E", -1);
  1053. mapToSortByValue.put("F", 1000);
  1054. mapToSortByValue.put("G", 79);
  1055. mapToSortByValue.put("H", 15);
  1056.  
  1057. // Sort all the map entries by value
  1058. Set<Map.Entry<String,Integer>> set = new TreeSet<Map.Entry<String,Integer>>(
  1059. new Comparator<Map.Entry<String,Integer>>(){
  1060. @Override
  1061. public int compare(Map.Entry<String,Integer> obj1, Map.Entry<String,Integer> obj2) {
  1062. Integer val1 = obj1.getValue();
  1063. Integer val2 = obj2.getValue();
  1064. // DUPLICATE VALUE CASE
  1065. // If the values are equals, we can't return 0 because the 2 entries would be considered
  1066. // as equals and one of them would be deleted (because we use a set, no duplicate, remember!)
  1067. int compareValues = val1.compareTo(val2);
  1068. if ( compareValues == 0 ) {
  1069. String key1 = obj1.getKey();
  1070. String key2 = obj2.getKey();
  1071. int compareKeys = key1.compareTo(key2);
  1072. if ( compareKeys == 0 ) {
  1073. // what you return here will tell us if you keep REAL KEY-VALUE duplicates in your set
  1074. // if you want to, do whatever you want but do not return 0 (but don't break the comparator contract!)
  1075. return 0;
  1076. }
  1077. return compareKeys;
  1078. }
  1079. return compareValues;
  1080. }
  1081. }
  1082. );
  1083. set.addAll(mapToSortByValue.entrySet());
  1084.  
  1085.  
  1086. // OK NOW OUR SET IS SORTED COOL!!!!
  1087.  
  1088. // And there's nothing more to do: the entries are sorted by value!
  1089. for ( Map.Entry<String,Integer> entry : set ) {
  1090. System.out.println("Set entries: " + entry.getKey() + " -> " + entry.getValue());
  1091. }
  1092.  
  1093.  
  1094.  
  1095.  
  1096. // But if you add them to an hashmap
  1097. Map<String,Integer> myMap = new HashMap<String,Integer>();
  1098. // When iterating over the set the order is still good in the println...
  1099. for ( Map.Entry<String,Integer> entry : set ) {
  1100. System.out.println("Added to result map entries: " + entry.getKey() + " " + entry.getValue());
  1101. myMap.put(entry.getKey(), entry.getValue());
  1102. }
  1103.  
  1104. // But once they are in the hashmap, the order is not kept!
  1105. for ( Integer value : myMap.values() ) {
  1106. System.out.println("Result map values: " + value);
  1107. }
  1108. // Also this way doesn't work:
  1109. // Logic because the entryset is a hashset for hashmaps and not a treeset
  1110. // (and even if it was a treeset, it would be on the keys only)
  1111. for ( Map.Entry<String,Integer> entry : myMap.entrySet() ) {
  1112. System.out.println("Result map entries: " + entry.getKey() + " -> " + entry.getValue());
  1113. }
  1114.  
  1115.  
  1116. // CONCLUSION:
  1117. // If you want to iterate on a map ordered by value, you need to remember:
  1118. // 1) Maps are only sorted by keys, so you can't sort them directly by value
  1119. // 2) So you simply CAN'T return a map to a sortMapByValue function
  1120. // 3) You can't reverse the keys and the values because you have duplicate values
  1121. // This also means you can't neither use Guava/Commons bidirectionnal treemaps or stuff like that
  1122.  
  1123. // SOLUTIONS
  1124. // So you can:
  1125. // 1) only sort the values which is easy, but you loose the key/value link (since you have duplicate values)
  1126. // 2) sort the map entries, but don't forget to handle the duplicate value case (like i did)
  1127. // 3) if you really need to return a map, use a LinkedHashMap which keep the insertion order
  1128.  
  1129. Set entries: E -> -1
  1130. Set entries: B -> 1
  1131. Set entries: A -> 3
  1132. Set entries: C -> 3
  1133. Set entries: D -> 5
  1134. Set entries: H -> 15
  1135. Set entries: G -> 79
  1136. Set entries: F -> 1000
  1137. Added to result map entries: E -1
  1138. Added to result map entries: B 1
  1139. Added to result map entries: A 3
  1140. Added to result map entries: C 3
  1141. Added to result map entries: D 5
  1142. Added to result map entries: H 15
  1143. Added to result map entries: G 79
  1144. Added to result map entries: F 1000
  1145. Result map values: 5
  1146. Result map values: -1
  1147. Result map values: 1000
  1148. Result map values: 79
  1149. Result map values: 3
  1150. Result map values: 1
  1151. Result map values: 3
  1152. Result map values: 15
  1153. Result map entries: D -> 5
  1154. Result map entries: E -> -1
  1155. Result map entries: F -> 1000
  1156. Result map entries: G -> 79
  1157. Result map entries: A -> 3
  1158. Result map entries: B -> 1
  1159. Result map entries: C -> 3
  1160. Result map entries: H -> 15
  1161.  
  1162. class MapUtil {
  1163.  
  1164. public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ){
  1165. ValueComparator<K,V> bvc = new ValueComparator<K,V>(map);
  1166. TreeMap<K,V> sorted_map = new TreeMap<K,V>(bvc);
  1167. sorted_map.putAll(map);
  1168. return sorted_map;
  1169. }
  1170.  
  1171. }
  1172.  
  1173. class ValueComparator<K, V extends Comparable<? super V>> implements Comparator<K> {
  1174.  
  1175. Map<K, V> base;
  1176. public ValueComparator(Map<K, V> base) {
  1177. this.base = base;
  1178. }
  1179.  
  1180. public int compare(K a, K b) {
  1181. int result = (base.get(a).compareTo(base.get(b)));
  1182. if (result == 0) result=1;
  1183. // returning 0 would merge keys
  1184. return result;
  1185. }
  1186. }
  1187.  
  1188. Map<String,Integer> tempMap=new HashMap<String,Integer>(inputUnsortedMap);
  1189. LinkedHashMap<String,Integer> sortedOutputMap=new LinkedHashMap<String,Integer>();
  1190.  
  1191. for(int i=0;i<inputUnsortedMap.size();i++){
  1192. Map.Entry<String,Integer> maxEntry=null;
  1193. Integer maxValue=-1;
  1194. for(Map.Entry<String,Integer> entry:tempMap.entrySet()){
  1195. if(entry.getValue()>maxValue){
  1196. maxValue=entry.getValue();
  1197. maxEntry=entry;
  1198. }
  1199. }
  1200. tempMap.remove(maxEntry.getKey());
  1201. sortedOutputMap.put(maxEntry.getKey(),maxEntry.getValue());
  1202. }
  1203.  
  1204. TreeMap<Integer, Collection<String>> sortedMap = new TreeMap<>(
  1205. Multimaps.invertFrom(Multimaps.forMap(originalMap),
  1206. ArrayListMultimap.<Integer, String>create()).asMap());
Add Comment
Please, Sign In to add comment