如何使用Java中的流进行n次迭代n
使用基本的循环,我写了以下内容:
Map<String, Integer> map = new HashMap<>();
for (int i=0; i < list.size(); i++) {
int id = list.get(i).getId();
ResponseEntity<Response> response = getDetail(id); //some method call
Integer totalUser = response.getBody().getData();
map.put(list.get(i).getUser , totalUser);
}
但是我想在Java 8中使用流以更好的方式编写它。
Using the basic for-loop, I have written the following :
Map<String, Integer> map = new HashMap<>();
for (int i=0; i < list.size(); i++) {
int id = list.get(i).getId();
ResponseEntity<Response> response = getDetail(id); //some method call
Integer totalUser = response.getBody().getData();
map.put(list.get(i).getUser , totalUser);
}
But I want to write this in a better way using stream in java 8.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过多种方式在此处更改摘要以使用Java-8流。
在这里,我直接概述了一些我的脑海。
让我们分解他们,解释他们的差异更多。
1。
此人使用MethodReferences将所需的函数传递到
流#MAP(function)
方法。它可以读为'映射项目,即iDwrapper-objects,并通过在每个对象上调用idwrapper#getId()
来完成此操作溪流'。之后,完成了对流#MAP(function)
进行的另一个调用,但是这次操作的对象是'this'(我为示例创建的虚拟类)并调用#getDetails( INT)
在此类上。2。
这个完全等于1。但是使用通常的lambda表达来实现相同的表达。
3。
在这种情况下,我们将功能定义为LAMDA,而只是链接该方法类。
如前所述,还有很多其他可能性,但这里有很少的教育。希望我能帮助您更好地了解流。
There are multiple ways you could change your snippet here to use Java-8 Streams.
Here an overview of a few straight out of my head.
Let's break them down and explain their differences a bite more.
1.
This one uses MethodReferences to pass the desired functions down the
Stream#map(Function)
method. It can be read as 'map the items, which are IDWrapper-Objects and do it by callingIDWrapper#getId()
on every object and put the resulting items (integer values in this case) back into the stream'. Afterwards another call toStream#map(Function)
is done but this time the object to operate on is 'this' (my dummy class i created for the example) and call the#getDetails(int)
method on this class.2.
This one is quite simply equal to 1. but using usual lambda expression to achieve the same.
3.
In this case we're defining the function as a lamda and simply chaining the method class.
As mentioned before there are lots of other possibilities, but here are an education few. Hope I could help you understanding streams a little bit better.
类似:
----编辑-------
何ho ...这正是Holger的评论。在应得的信用额的地方给予信用。
Something like:
----EDIT----
Ho ho... This is exactly Holger's comment. Give credit where credit is due.