[英]Find a map in list of map java stream
我正在迭代Hashmap列表,使用以下代碼查找所需的HashMap對象。
public static Map<String, String> extractMap(List<Map<String, String>> mapList, String currentIp) {
for (Map<String, String> asd : mapList) {
if (asd.get("ip").equals(currentIp)) {
return asd;
}
}
return null;
}
我在考慮使用Java 8流。 這是我用來顯示所需對象的代碼。
public static void displayRequiredMapFromList(List<Map<String, String>> mapList, String currentIp) {
mapList.stream().filter(e -> e.get("ip").equals(currentIp)).forEach(System.out::println);
}
我無法使用以下代碼從流中獲取所需的Map
public static Map<String, String> extractMapByStream(List<Map<String, String>> mapList, String currentIp) {
return mapList.stream().filter(e -> e.get("ip").equals(currentIp))
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
}
這會導致語法錯誤類型不匹配:無法從Map轉換為Map 。 我有什么需要放在這里獲取地圖?
你不想。 .collect
任何東西。 您想要找到與謂詞匹配的第一個地圖。
所以你應該使用.findFirst()
而不是.collect()
。
toMap()
用於從流中的元素構建Map
。
但是你不想這樣做,每個元素都已經是一個Map
。
用戶這個
public static Map<String, String> extractMapByStream(List<Map<String, String>> mapList, String currentIp) {
return mapList.stream().filter(e -> e.get("ip").equals(currentIp))
.findFirst().get();
}
這將是有效的,沒有orElse()
的其他示例不會編譯(至少它們不在我的IDE中)。
mapList.stream()
.filter(asd -> asd.get("ip").equals(currentIp))
.findFirst()
.orElse(null);
作為建議我唯一要添加的是返回Collections.emptyMap()
,這將在調用代碼中保存空檢查。
要在沒有orElse
情況下編譯代碼,您需要將方法簽名更改為:
public static Optional<Map<String, String>> extractMap(List<Map<String, String>> mapList, String currentIp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.