###问题描述
将一个List按照某种条件分组
[1, 2, 3, 4]->{OddNumber=[1, 3], EvenNumber=[2, 4]}
public static String getKey(Integer input) {
return input % 2 == 0 ? "EvenNumber" : "OddNumber";
}
###原来
Map<String, List<Integer>> group = Maps.newHashMap();
for (Integer integer : source) {
String key = getKey(integer);
if (!group.containsKey(key)) {
group.put(key, Lists.<Integer>newArrayList());
}
group.get(key).add(integer);
}
###使用Guava
Map<String, List<Integer>> group = Multimaps.asMap(
Multimaps.index(source, new Function<Integer, String>() {
public String apply(Integer input) {
return getKey(input);
}
})
);
或
Map<String, Collection<Integer>> group = Multimaps.index(source,
new Function<Integer, String>() {
public String apply(Integer input) {
return getKey(input);
}
}).asMap();
只需要关注key时怎么实现的就行