[英]lambda Java 8, how to map a list that is a filed of the result of filter operation
[英]How to use Map filter in list by Java 8 lambda
Map是Map<String, List<User>>
並且List是List<User>
。 我想用
Map<String,List<User>> newMap = oldMap.stream()
.filter(u ->userList.stream()
.filter(ul ->ul.getName().equalsIgnoreCase(u.getKey()).count()>0))
.collect(Collectors.toMap(u.getKey, u.getVaule()));
無法更改為新的Map
。 為什么?
也許您打算創建輸入Map的條目Set的Stream。
Map<String,List<User>> newMap =
oldMap.entrySet().stream()
.filter(u ->userList.stream().filter(ul ->ul.getName().equalsIgnoreCase(u.getKey())).count()>0)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
這將創建一個Map
,保留原始Map
的條目,這些條目的鍵等於userList
成員中至少一個成員的名稱(忽略大小寫)。
您的代碼有幾個問題:
Map
沒有stream()
:它的條目集有,所以您需要先調用entrySet()
。 Collectors.toMap
代碼不正確:您需要使用lambda u -> u.getKey()
(或方法引用Map.Entry::getKey
),而不僅僅是表達式u.getKey()
。 另外,您拼寫了getValue()
。 這將是一個更正的代碼:
Map<String, List<User>> newMap =
oldMap.entrySet()
.stream()
.filter(u -> userList.stream()
.filter(ul ->ul.getName().equalsIgnoreCase(u.getKey())).count() > 0
).collect(Collectors.toMap(u -> u.getKey(), u -> u.getValue()));
但是這里有幾點注意事項:
anyMatch(predicate)
。 這是一個簡短的終端操作,如果謂詞對於Stream中的至少一個元素為true
,則返回true
。 這還有一個優點,即此操作可能不會處理Stream中的所有元素(過濾時會處理) userList
。 最好使用具有O(1)查找的Set
(因此,首先將userList
轉換為userSet
,將用戶名轉換為小寫,然后在該set中搜索小寫值的用戶名)。 。 這將是一個性能更高的代碼:
Set<String> userNameSet = userList.stream().map(u -> u.getName().toLowerCase(Locale.ROOT)).collect(toSet());
Map<String,List<User>> newMap =
oldMap.entrySet()
.stream()
.filter(u -> userNameSet.contains(u.getKey().toLowerCase(Locale.ROOT)))
.collect(Collectors.toMap(u -> u.getKey(), u -> u.getValue()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.