Java 8 即将发布...在学习 Streams 时,我遇到了一个关于使用一种新方法对字谜进行分组的场景。我面临的问题是我找不到使用 map/reduce 函数对字符串对象进行分组的方法。相反,我必须创建与Aggregate Operations - Reduction中记录的类似方式。
根据文档,我们可以简单地使用:
LIST<T>.stream().collect(Collectors.groupingBy(POJO::GET_METHOD))
所以这Collectors.groupingBy()
将根据使用的方法聚合地图的键。然而,这种方法对于包装一个简单的字符串表示来说似乎太麻烦了。
public class AnagramsGrouping {
static class Word {
public String original;
public Word(String word) {
original = word;
}
public String getKey() {
char[] characters = input.toCharArray();
Arrays.sort(characters);
return new String(characters);
}
public String toString() {
return original;
}
}
public static void main(String[] args) {
List<Word> words = Arrays.asList(new Word("pool"), new Word("loop"),
new Word("stream"), new Word("arc"), new Word("odor"),
new Word("car"), new Word("rood"), new Word("meats"),
new Word("fires"), new Word("fries"), new Word("night"),
new Word("thing"), new Word("mates"), new Word("teams"));
Map<String, List<Word>> anagrams = words.stream().collect(
Collectors.groupingBy(Word::getKey));
System.out.println(anagrams);
}
}
这将打印以下内容:
{door=[odor, rood], acr=[arc, car], ghint=[night, thing],
aemrst=[stream], efirs=[fires, fries], loop=[pool, loop],
aemst=[meats, mates, teams]}
相反,我正在寻找一种更简单、更直接的解决方案,它使用新的 map/reduce 函数将结果累积到类似的界面Map<String, List<String>
中。基于How to convert List to Map,我有以下内容:
List<String> words2 = Arrays.asList("pool", "loop", "stream", "arc",
"odor", "car", "rood", "meats", "fires", "fries",
"night", "thing", "mates", "teams");
words2.stream().collect(Collectors.toMap(w -> sortChars(w), w -> w));
但是这段代码会产生一个键冲突,因为它是一个 1-1 的映射。
Exception in thread "main" java.lang.IllegalStateException: Duplicate key pool
这是有道理的......有没有办法将它们分组到与第一个解决方案类似的输出中groupingBy
,但不使用包装值的POJO?