user871611
user871611

Reputation: 3461

Combining Streams

I'm trying to eliminate the below temporary Map and combine it into one Stream. I tried a little here and there, but came up with no solution. So there is no code what I can present so far, since my approaches would probably be misleading.

final Map<String, String> tempCountryMap = iso3166Alpha2CountryCodes.stream() //
  .collect(Collectors.toMap(cc -> cc, cc -> new Locale("", cc).getDisplayCountry(locale)));

final Map<String, String> sortedMap = tempCountryMap.entrySet().stream() //
  .sorted(Map.Entry.comparingByValue(Collator.getInstance(locale))) //
  .collect(Collectors.toMap(Entry<String, String>::getKey, Entry<String, String>::getValue, (e1, e2) -> e2,
      LinkedHashMap::new));

Upvotes: 1

Views: 90

Answers (1)

Eran
Eran

Reputation: 393771

You can do it in a single pipeline if you map the elements of the original Stream to Map.Entrys and then proceed with the sorting:

final Map<String, String> sortedMap = 
    iso3166Alpha2CountryCodes.stream()
                             .map(cc -> new SimpleEntry<>(cc,new Locale("", cc).getDisplayCountry(locale)))
                             .sorted(Map.Entry.comparingByValue(Collator.getInstance(locale)))
                             .collect(Collectors.toMap(Map.Entry::getKey, 
                                                       Map.Entry::getValue, 
                                                       (e1, e2) -> e2,
                                                       LinkedHashMap::new));

Upvotes: 1

Related Questions