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.
CodePudding user response:
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.
List<IDWrapper> list = IntStream.range( 0, 20 ).mapToObj( IDWrapper::new ).collect( Collectors.toList() );
List<String> details = list.stream().map( IDWrapper::getId ).map( this::getDetails ).collect( Collectors.toList() );
List<String> details2 = list.stream().map( item -> item.getId() ).map( id -> getDetails( id ) ).collect( Collectors.toList() );
List<String> details3 = list.stream().map( item -> getDetails( item.getId() ) ).collect( Collectors.toList() );
Let's break them down and explain their differences a bite more.
1.
List<String> details = list.stream().map( IDWrapper::getId ).map( this::getDetails ).collect( Collectors.toList() );
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 calling IDWrapper#getId()
on every object and put the resulting items (integer values in this case) back into the stream'. Afterwards another call to Stream#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.
List<String> details2 = list.stream().map( item -> item.getId() ).map( id -> getDetails( id ) ).collect( Collectors.toList() );
This one is quite simply equal to 1. but using usual lambda expression to achieve the same.
3.
List<String> details3 = list.stream().map( item -> getDetails( item.getId() ) ).collect( Collectors.toList() );
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.
CodePudding user response:
Something like:
Map<String,Integer> m =
list.stream()
.collect(Collectors.toMap(e -> e.getUser, // key extractor
e -> getDetail(e.getId()).getBody().getData() // value extractor
)
);
----EDIT----
Ho ho... This is exactly Holger's comment. Give credit where credit is due.