i am expecting the result in sorted order. But the result is different. Please help me to sort by key.
Also i tried first to have a sorted list and then from that list to Map. Even that is not working as expected.
Am expecting like this
Key is GR Value is Germany Key is IN Value is India Key is UK Value is United Kingdom Key is US Value is United States
Country.java
public class Country {
private String countryCode;
private String countryName;
public Country(String countryCode, String countryName) {
super();
this.countryCode = countryCode;
this.countryName = countryName;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
@Override
public String toString() {
return "Country [countryCode=" + countryCode + ", countryName=" + countryName + "]";
}
}
Logic
public class Java8_2_ListToMap {
public static void main(String[] args) {
Map<String, String> countryMaps1 = getSortedCountryMap(getCountryLists());
countryMaps1.forEach((k, v) -> System.out.println("Key is " + k + " Value is " + v));
}
private static List<Country> getCountryLists() {
return Arrays.asList(new Country("IN", "India"), new Country("US", "United States"),
new Country("GR", "Germany"), new Country("UK", "United Kingdom"));
}
private static Map<String, String> getSortedCountryMap(List<Country> countryLists) {
Map<String, String> countryMap = countryLists.stream()
.sorted(Comparator.comparing(Country::getCountryCode))
.collect(Collectors.toMap(Country::getCountryCode, Country::getCountryName));
return countryMap;
}
}
Output is
Key is IN Value is India
Key is UK Value is United Kingdom
Key is GR Value is Germany
Key is US Value is United States