我正在使用Java 8和forEach迭代一个地图,如下所示
Map<Integer,String> testMap = new HashMap<>();
testMap.put(1, "Atul");
testMap.put(2, "Sudeep");
testMap.put(3, "Mayur");
testMap.put(4, "Suso");
testMap.entrySet().forEach( (K)-> {
System.out.println("Key ="+K.getKey()+" Value = "+K.getValue());
System.out.println("Some more processing ....");
}
);我的问题是:
1)在地图中进行处理时,如何从forEach中提取方法?
2)也就是说,forEach中的代码部分应该包装在方法中:
System.out.println("Key ="+K.getKey()+" Value = "+K.getValue());
System.out.println("Some more processing ...."); 3)我理解forEach方法在这种情况下需要一个Consumer函数接口,该接口具有以下签名-
void accept(T t); 我想要的是这样的东西:
//declare a consumer object
Consumer<Map.Entry<Integer,String>> processMap = null;
// and pass it to ForEach
testMap.entrySet().forEach(processMap);5)我们能否做到这一点?
发布于 2019-07-02 11:49:12
我理解forEach方法在本例中需要一个消费者函数接口,它具有以下签名
forEach()确实需要一个Consumer,但是要处理一个Consumer,不一定需要Consumer。您需要的是尊重Consumer功能接口的输入/输出的方法,即Entry<Integer,String>输入/ void输出。
因此,您只需调用一个以参数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>>的forEach(),例如:
Consumer<Map.Entry<Integer,String>> consumer = this::useEntry;
//...used then :
testMap.entrySet().forEach(consumer);只有当您的forEach()中的使用者被设计成以某种方式(由客户端计算/传递或无论如何都是由客户端计算/传递)时才有意义。
如果您不是在这种情况下,您使用的消费者,您最终使事情更抽象和复杂,这是有效的要求。
发布于 2019-07-02 11:49:31
关于
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));发布于 2019-07-02 11:35:55
您可以使用方法引用:
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 ....");
}https://stackoverflow.com/questions/56851508
复制相似问题