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, thereforeSortedMap / TreeMapwould require some very custom/hardcoded comparator:Output:
Another approach would be to use
LinkedHashMapcapable of maintaining the insertion order and fix this order as necessary:Similar approach would be to use an unsorted map and a list of keys in the desired order.
However, it seems that method
addof the custom object requires both key and value anyway, so the order of populating the fields should not be relevant.