I have a list of Objects consisting of only two fields. I want to convert it into Pair for easy access to fields for further process. In the following code, I am doing two streams to get the Pair and I intend to do it in a single stream.
What could be the best way to combine these two streams?
List<Long> activeUserIds = activeUserIdAndTokenResults.stream().map(AppRegistrationRepository.ActiveUserIdAndTokenResult::getUserId).collect(Collectors.toList());
List<String> activeTokens = activeUserIdAndTokenResults.stream().map(AppRegistrationRepository.ActiveUserIdAndTokenResult::getToken).collect(Collectors.toList());
return Pair.of(activeUserIds, activeTokens);
For Pair, I have used org.apache.commons.lang3.tuple
CodePudding user response:
It seems your data contains both ID and token information already so you can get a Stream<Pair> directly:
Stream<Pair> sp = activeUserIdAndTokenResults.stream().map(e -> Pair.of(
AppRegistrationRepository.ActiveUserIdAndTokenResult.getUserId(e),
AppRegistrationRepository.ActiveUserIdAndTokenResult.getToken(e))
);
CodePudding user response:
Assuming you actually intend to return a pair of lists, you can use the Pair as your collector:
return activeUserIdAndTokenResults.stream().collect(
() -> Pair.of(new ArrayList<>(), new ArrayList<>()),
(p, r) -> {
p.getLeft().add(r.getUserId());
p.getRight().add(r.getToken());
},
(p1, p2) -> {
p1.getLeft().addAll(p2.getLeft());
p2.getRight().addAll(p2.getRight());
});
Just remember that streams are not always an improvement over old-fashioned loops.
CodePudding user response:
public List<Pair<Long, String> convert(List<AppRegistrationRepository.ActiveUserIdAndTokenResult> results){
return results.stream().map(r -> Pair.of(r.getUserId(), r.getToken())).collect(Collectors.toList());
}
