我有以下代码。
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public final class Main {
public static void main(final String[] args) {
final Object[][] pairs = { { "Arka Gdynia", Collections.emptyList() },
{ "Legia Warszawa", Collections.emptyList() }, { "ŁKS Łódź", Collections.emptyList() },
{ "Śląsk Wrocław", Collections.emptyList() }, { "Wisła Kraków", Collections.emptyList() }, };
final Map<String, Object> clubPlayerMap = Arrays.stream(pairs)
.collect(Collectors.toMap(c -> c[0].toString(), c -> c[1], (o1, o2) -> o1, TreeMap::new));
for (final String key : clubPlayerMap.keySet()) {
System.out.println(key);
}
}
}
不幸的是,这并没有产生我想要的结果。密钥需要根据波兰语归类进行排序。
Arka Gdynia
Legia Warszawa
Wisła Kraków
ŁKS Łódź
Śląsk Wrocław
我期望的结果是
Arka Gdynia
Legia Warszawa
ŁKS Łódź
Śląsk Wrocław
Wisła Kraków
因此,我用Google搜索并找到了一种使用
java.text.Collator
做到这一点的方法。但是,我想知道是否有可能与stream()
和collect()
一起作为单线执行。我想出的解决方案如下,但是不幸的是,它并不是很整洁。
import java.text.Collator;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public final class Main {
public static void main(final String[] args) {
final Object[][] pairs = { { "Arka Gdynia", Collections.emptyList() },
{ "Legia Warszawa", Collections.emptyList() }, { "ŁKS Łódź", Collections.emptyList() },
{ "Śląsk Wrocław", Collections.emptyList() }, { "Wisła Kraków", Collections.emptyList() }, };
final Map<String, Object> clubPlayerMapCollated = new TreeMap<>(Collator.getInstance(new Locale("pl", "PL")));
final Map<String, Object> clubPlayerMap = Arrays.stream(pairs)
.collect(Collectors.toMap(c -> c[0].toString(), c -> c[1], (o1, o2) -> o1, TreeMap::new));
clubPlayerMapCollated.putAll(clubPlayerMap);
for (final String key : clubPlayerMapCollated.keySet()) {
System.out.println(key);
}
}
}
可以单线生成地图吗?
最佳答案
而不是将方法引用传递给默认构造函数(TreeMap::new
),而是传递可以生成所需TreeMap
的lambda表达式:
final Map<String, Object> clubPlayerMap =
Arrays.stream(pairs)
.collect(Collectors.toMap(c -> c[0].toString(),
c -> c[1],
(o1, o2) -> o1,
() -> new TreeMap<>(Collator.getInstance(new Locale("pl", "PL")))));
关于java - 使用Collator在一行中收集到TreeMap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59443960/