Java Map sort on key and store new map via LinkedHashMap

Description

Java Map sort on key and store new map via LinkedHashMap

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class Main {

  public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();

    map.put("KeyA", "Java");
    map.put("KeyC", "CSS");
    map.put("KeyD", "JAVA");
    map.put("KeyB", "SQL");
    map.put("KeyS", "Dart");
    map.put("KeyE", "C++");
    map.put("KeyG", "Javascript");

    map = sort(map, new Comparator<String>() {
      @Override//  w w  w .ja v a 2 s. c  om
      public int compare(String o1, String o2) {
        return o1.compareTo(o2);
      }
    });

    System.out.println(map);
  }

  @SuppressWarnings("unchecked")
  public static <K, V> Map<K, V> sort(Map<K, V> in, Comparator<? super V> compare) {
    Map<K, V> result = new LinkedHashMap<K, V>();

    V[] array = (V[]) in.values().toArray();
    for (int i = 0; i < array.length; i++) {

    }
    Arrays.sort(array, compare);
    
    for (V item : array) {
      K key = (K) getKey(in, item);
      result.put(key, item);
    }
    return result;
  }

  public static <K, V> Object getKey(Map<K, V> in, V value) {
    Set<K> key = in.keySet();
    Iterator<K> keyIterator = key.iterator();
    while (keyIterator.hasNext()) {
      K valueObject = (K) keyIterator.next();
      if (in.get(valueObject).equals(value)) {
        return valueObject;
      }
    }
    return null;
  }
}



PreviousNext

Related