3 回答

TA貢獻1815條經(jīng)驗 獲得超6個贊
我理解這種情況下的 forEach 方法需要一個具有以下簽名的消費者功能接口
forEach()確實期望 aConsumer但要處理 aConsumer你不一定需要 a Consumer。您需要的是一種尊重功能接口的輸入/輸出的方法Consumer,即Entry<Integer,String>輸入/void輸出。
因此,您可以只調(diào)用一個方法,該方法的參數(shù)為Entry:
testMap.entrySet().forEach(k-> useEntry(k)));
或者
testMap.entrySet().forEach(this::useEntry));
使用 useEntry() 例如:
private void useEntry(Map.Entry<Integer,String> e)){
System.out.println("Key ="+e.getKey()+" Value = "+e.getValue());
System.out.println("Some more processing ....");
}
Consumer<Map.Entry<Integer,String>>聲明您傳遞給的a ,forEach()例如:
Consumer<Map.Entry<Integer,String>> consumer = this::useEntry;
//...used then :
testMap.entrySet().forEach(consumer);
僅當(dāng)您的消費者forEach()被設(shè)計為以某種方式可變(由客戶端計算/傳遞或無論如何)時才有意義。
如果您不是這種情況并且您使用了消費者,那么您最終會使事情變得比實際需要的更加抽象和復(fù)雜。

TA貢獻1887條經(jīng)驗 獲得超5個贊
關(guān)于什么
public void processMap(Map.Entry K){
System.out.println("Key ="+K.getKey()+" Value = "+K.getValue());
System.out.println("Some more processing ....");
}
然后像這樣使用它:
testMap.entrySet().forEach((K)-> processMap(K));

TA貢獻1825條經(jīng)驗 獲得超4個贊
您可以使用方法參考:
Consumer<Map.Entry<Integer,String>> processMap = SomeClass::someMethod;
該方法定義為:
public class SomeClass {
public static void someMethod (Map.Entry<Integer,String> entry) {
System.out.println("Key ="+entry.getKey()+" Value = "+entry.getValue());
System.out.println("Some more processing ....");
}
}
如果您愿意,您甚至可以使該方法更通用:
public static <K,V> void someMethod (Map.Entry<K,V> entry) {
System.out.println("Key ="+entry.getKey()+" Value = "+entry.getValue());
System.out.println("Some more processing ....");
}
添加回答
舉報