我正在尝试理解一个编程问题,例如,我给了一个单词列表,(苹果,橙色,汽车,可以,模糊)我会得到一个哈希映射,其中包含键的长度和值的链接列表。例如,
(3, {car, can})
(5, {apple, fuzzy})
(6, {orange})
我怎么能建立这个?我是Java的新手,只知道如何读取字符串输入并获取每个字符串的长度。但是对哈希映射非常不熟悉。有人能引导我朝正确的方向发展吗?
答案 0 :(得分:1)
正如Tim Biegeleisen所说,如果你正在使用Java 8,这是一种方法:
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class CollectByLength {
public static void main(String[] args) {
Map<Integer, List<String>> map = Stream.of("apple", "orange", "car", "can", "fuzzy")
.collect(groupingBy(String::length));
System.out.println(map); //prints {3=[car, can], 5=[apple, fuzzy], 6=[orange]}
}
}
如果您出于某种原因关心List
实施,上述解决方案并未对列表实施提供任何保证。来自doc:
不保证类型,可变性,可序列性或 返回的Map或List对象的线程安全性。
但也可以指定您需要的List
实施(LinkedList
此处)
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class CollectByLength {
public static void main(String[] args) {
Map<Integer, List<String>> map = Stream.of("apple", "orange", "car", "can", "fuzzy")
.collect(groupingBy(String::length, toCollection(LinkedList::new)));
System.out.println(map); //prints {3=[car, can], 5=[apple, fuzzy], 6=[orange]}
}
}
答案 1 :(得分:0)
这是一个相当简洁的Java 7方法:
List<String> words = Arrays.asList("apple", "orange", "car", "can", "fuzzy");
Map<Integer, List<String>> map = new HashMap<>();
for (String word : words) {
List<String> wordList = map.get(word.length());
if (wordList == null) {
wordList = new ArrayList<String>();
wordList.add(word);
map.put(word.length(), wordList);
}
else {
wordList.add(word);
}
}
我将让专家们给出一个更加精简的Java 8解决方案。