首页 > 解决方案 > 合并流

问题描述

我正在尝试消除下面的临时 Map 并将其合并为一个Stream。我在这里和那里尝试了一点,但没有找到解决方案。所以到目前为止我还没有可以展示的代码,因为我的方法可能会产生误导。

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));

标签: javajava-stream

解决方案


如果将原始元素映射StreamMap.Entrys 然后继续排序,则可以在单个管道中执行此操作:

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));

推荐阅读