Пример #1
0
  private static LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
    List mapKeys = new ArrayList(passedMap.keySet());
    List mapValues = new ArrayList(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);

    LinkedHashMap sortedMap = new LinkedHashMap();

    Iterator valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
      Object val = valueIt.next();
      Iterator keyIt = mapKeys.iterator();

      while (keyIt.hasNext()) {
        Object key = keyIt.next();
        String comp1 = passedMap.get(key).toString();
        String comp2 = val.toString();

        if (comp1.equals(comp2)) {
          passedMap.remove(key);
          mapKeys.remove(key);
          sortedMap.put(key, val);
          break;
        }
      }
    }
    return sortedMap;
  }
Пример #2
0
  private static Map<String, Double> sortByComparator(
      Map<String, Double> map, final boolean order) {
    List<Entry<String, Double>> list = new LinkedList<Entry<String, Double>>(map.entrySet());

    // Sorting the list based on values
    Collections.sort(
        list,
        new Comparator<Entry<String, Double>>() {
          public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            if (order) {
              return o1.getValue().compareTo(o2.getValue());
            } else {
              return o2.getValue().compareTo(o1.getValue());
            }
          }
        });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
    for (Entry<String, Double> entry : list) {
      sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
  }