我確信這很簡單,但由于某種原因我沒有得到我想要的。我有一個SortedMap<String, String>值,我想對其進行流式傳輸和過濾并僅保存一些值。例如: SortedMap<String, String> input = new TreeMap<>(); values.put("accepted.animal", "dog"); values.put("accepted.bird", "owl"); values.put("accepted.food", "broccoli"); values.put("rejected.animal", "cat"); values.put("rejected.bird", "eagle"); values.put("rejected.food", "meat");我只想保留密鑰中包含“accepted”的值并刪除其他所有內容。所以,結果將是:{accepted.animal=dog, accepted.bird=owl, accepted.food=broccoli}如何流式傳輸地圖并過濾掉除包含“已接受”的鍵之外的所有內容?這是我嘗試過的:private SortedMap<String, String> process(final Input input) { final SortedMap<String, String> results = new TreeMap<>(); return input.getInputParams() .entrySet() .stream() .filter(params -> params.getKey().contains("accepted")) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));} 但由于“無法從靜態上下文引用非靜態方法”而失敗。
2 回答

一只甜甜圈
TA貢獻1836條經驗 獲得超5個贊
您需要使用另一種變體Collectors.toMap
,以便傳遞合并函數和供應商以在TreeMap
那里收集:
return?input.getInputParams() ????????.entrySet() ????????.stream() ????????.filter(params?->?params.getKey().startsWith("accepted"))?//?small?change ????????.collect(Collectors.toMap(Map.Entry::getKey,?Map.Entry::getValue, ????????????????(a,?b)?->?b,?TreeMap::new));

慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
最終,該方法不會編譯,因為Collectors.toMap()返回Map,而方法簽名需要返回類型為SortedMap。
我不知道誤導性的“靜態上下文”錯誤消息背后的原因;但是當我嘗試使用 Gradle 構建代碼時,我收到了一條稍微有用的消息。
error: incompatible types: inference variable R has incompatible bounds
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
^
equality constraints: Map<K,U>
lower bounds: SortedMap<String,String>,Object
Collectors.toMap()您可能需要接受 a的重載版本Supplier<Map>,以便您可以提供SortedMapfor 輸出。
添加回答
舉報
0/150
提交
取消