我想使用Java 8的流和lambdas将对象列表转换为Map.
这就是我在Java 7及以下版本中编写它的方法.
private Map<String, Choice> nameMap(List<Choice> choices) {
final Map<String, Choice> hashMap = new HashMap<>();
for (final Choice choice : choices) {
hashMap.put(choice.getName(), choice);
}
return hashMap;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用Java 8和Guava轻松完成此任务,但我想知道如何在没有Guava的情况下完成此操作.
在番石榴:
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, new Function<Choice, String>() {
@Override
public String apply(final Choice input) {
return input.getName();
}
});
}
Run Code Online (Sandbox Code Playgroud)
还有Java 8 lambda的番石榴.
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
Run Code Online (Sandbox Code Playgroud) 我有一个ArrayListJava的Collection类,如下所示:
ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
Run Code Online (Sandbox Code Playgroud)
如您所见,它animals ArrayList由3个bat元素和一个owl元素组成.我想知道Collection框架中是否有任何API返回bat出现次数或是否有另一种方法来确定出现次数.
我发现Google的Collection Multiset确实有一个API,可以返回元素的总出现次数.但这只与JDK 1.5兼容.我们的产品目前是JDK 1.6,所以我不能使用它.