[英]Given a list of strings, create a hashmap with length and string
I am trying to understand a programming question where I am given a list of words for example, (apple, orange, car, can, fuzzy) I would get a hashmap with the length for the key and linkedlist of words for value. 我试图理解一个编程问题,在该问题中,我得到了一个单词列表,例如(苹果,橘子,汽车,罐头,模糊),我将得到一个哈希图,其中包含键的长度和单词的链表的价值。 For example, 例如,
(3, {car, can})
(5, {apple, fuzzy})
(6, {orange})
How could I build this? 我该如何构建? I am relatively new to Java and only knows how to read string input and get the length of each string. 我对Java比较陌生,只知道如何读取字符串输入并获取每个字符串的长度。 But very unfamiliar with hashmaps. 但是非常不熟悉哈希图。 Could someone guide me in the right direction? 有人可以指引我正确的方向吗?
As Tim Biegeleisen said, here's an approach if you're using Java 8: 正如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]}
}
}
If you care about the List
implementation for some reason, the above solution doesn't provide any guarantee on the list implementation. 如果您出于某种原因关心List
实现,则上述解决方案不能保证List实现。 From the doc: 从文档中:
There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List objects returned. 不能保证返回的Map或List对象的类型,可变性,可序列化性或线程安全性。
But it's also possible to specify the List
implementation you need ( LinkedList
here) 但是也可以指定所需的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]}
}
}
Here is a fairly concise Java 7 approach: 这是一种相当简洁的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);
}
}
I will leave it up the experts to give an even leaner Java 8 solution. 我会留给专家来提供更精简的Java 8解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.