简体   繁体   中英

Sorting a entrySet<String, String> by keys

In my entrySet I have the next values:

name -> "someName"
nameSpace -> "someNameSpace"
version -> "someVersion"

I'm iterating over this entrySet and adding its values to a final object, my problem is that I need to add the values in the order:

nameSpace -> "someNameSpace"
name -> "someName"
version -> "someVersion"

With nameSpace first. Not pretty sure if it's possible to achieve that using a stream or something more sophisticated. I'm doing the process manually.

public static void main(String [] args){
     SortedMap<String, String> coordinates = new TreeMap<>();
    coordinates.put("name", "nameValue");
    coordinates.put("nameSpace", "nameSpaceValue");
    coordinates.put("version", "versionValue");
    String name = coordinates.get("name");
    String nameSpace = coordinates.get("nameSpace");
    String version = coordinates.get("version");

    /*Object.add("name", name);
    Object.add("nameSpace", nameSpace);
    Object.add("version", version);*/
}

Thanks!

It seems natural sorting is not applicable to the keys in this specific order: nameSpace, name, version , therefore SortedMap / TreeMap would require some very custom/hardcoded comparator:

SortedMap<String, String> coordinates = new TreeMap<>(
    (a, b) -> b.startsWith(a) && !a.startsWith(b) ? 1 : a.compareTo(b)
);
coordinates.put("version", "versionValue");
coordinates.put("nameSpace", "nameSpaceValue");
coordinates.put("name", "nameValue");

// iterating the map
// coordinates.forEach((k, v) -> Object.add(k, v));
coordinates.forEach((k, v) -> System.out.println(k + " -> " + v));

Output:

nameSpace -> nameSpaceValue
name -> nameValue
version -> versionValue

Another approach would be to use LinkedHashMap capable of maintaining the insertion order and fix this order as necessary:

Map<String, String> coordinates = new LinkedHashMap<>();
// add entries in expected order
coordinates.put("nameSpace", "nameSpaceValue");
coordinates.put("name", "nameValue");
coordinates.put("version", "versionValue");

Similar approach would be to use an unsorted map and a list of keys in the desired order.

Map<String, String> coordinates = new HashMap<>();    
coordinates.put("name", "nameValue");
coordinates.put("nameSpace", "nameSpaceValue");
coordinates.put("version", "versionValue");

List<String> keyOrder = Arrays.asList("nameSpace", "name", "version");
keyOrder.forEach(k -> System.out.println(k + " -> " + coordinates.get(k)));

However, it seems that method add of the custom object requires both key and value anyway, so the order of populating the fields should not be relevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM