我想出了以下方法,它确实有效,但我觉得应该有一种更干净的单线方式,它不依赖于“外部”地图(result
如下):
public TreeMap<Integer, HashSet<String>> mapLenToString(List<String> strings){
TreeMap<Integer, HashSet<String>> result = new TreeMap<>();
strings.stream()
.forEach(s -> {
int len = s.length();
if (result.containsKey(len)) {
HashSet<String> larger = result.get(len);
larger.add(s);
result.replace(len, larger);
}
else {
HashSet<String> newSet = new HashSet<>();
newSet.add(s);
result.put(len, newSet);
}
});
return result;
}