我有一個清單。String
我想將每個字串作為鍵存盤,將字串的長度作為值存盤在Map(比如HashMap)中。
我無法實作它。
List<String> ls = Arrays.asList("James", "Sam", "Scot", "Elich");
Map<String,Integer> map = new HashMap<>();
Function<String, Map<String, Integer>> fs = new Function<>() {
@Override
public Map<String, Integer> apply(String s) {
map.put(s,s.length());
return map;
}
};
Map<String, Integer> nmap = ls
.stream()
.map(fs).
.collect(Collectors.toMap()); //Lost here
System.out.println(nmap);
所有字串都是唯一的。
uj5u.com熱心網友回復:
無需像您創建的函式那樣用自己的map包裝每個字串。
相反,您需要在呼叫時提供正確的引數Collectors.toMap():
keyMapper- 負責從流元素中提取密鑰的函式。valueMapper-從流元素生成值的函式。
因此,您需要將流元素本身作為我們可以使用的鍵Function.identity(),這比 lambda 更具描述性str -> str,但完全相同。
Map<String,Integer> lengthByStr = ls.stream()
.collect(Collectors.toMap(
Function.identity(), // extracting a key
String::length // extracting a value
));
如果源串列可能包含重復項,您需要提供第三個引數 -負責解決重復項的mergeFunction 。
Map<String,Integer> lengthByStr = ls.stream()
.collect(Collectors.toMap(
Function.identity(), // key
String::length, // value
(left, right) -> left // resolving duplicates
));
uj5u.com熱心網友回復:
你說不會有重復的字串。但是,如果您可以使用distinct()它來確保它不會引起問題。
a-> a是使用流值的簡寫。本質上是一個回傳其引數的 lambda。distinct()洗掉任何重復的字串
Map<String, Integer> result = names.stream().distinct()
.collect(Collectors.toMap(a -> a, String::length));
處理重復的另一種方法是在Alexander Ivanchenko 的第二個toMap答案中。
如果你想得到 a 的長度String,你可以立即做 as someString.length()。但是假設您想要獲取以特定長度為鍵的所有字串的映射。您可以使用Collectors.groupingBy()默認情況下將重復項放在串列中來執行此操作。在這種情況下,副本將是字串的長度。
- 使用
length字串的作為鍵。 - 該值將是 a
List<String>以保存與該長度匹配的所有字串。
List<String> names = List.of("James", "Sam", "Scot",
"Elich", "lucy", "Jennifer","Bob", "Joe", "William");
Map<Integer, List<String>> lengthMap = names.stream()
.distinct()
.collect(Collectors.groupingBy(String::length));
lengthMap.entrySet().forEach(System.out::println);
印刷
3=[Sam, Bob, Joe]
4=[Scot, lucy]
5=[James, Elich]
7=[William]
8=[Jennifer]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/485454.html
