Reputation: 195
I want know is it even possible in Java to iterate over, let say a list, and get/set the same index(int) value of other list?
for (Response e : responseList) {
e.setPrimarySkills(requestList.get(??).getPrimarySkills());
}
Since it can't be done through model mapper because of the issues, is there any neat way of doing the same ?
Upvotes: 2
Views: 615
Reputation: 21055
One approach is to stream over each index and retrieve the elements pairwise using them:
IntStream.range(0, requestList.size()).forEach(i ->
responseList.get(i)
.setPrimarySkills(requestList.get(i).getPrimarySkills()));
Upvotes: 0
Reputation: 21055
Here's a solution using the StreamEx library, zipping the two lists together (pairwise) using zipWith
:
StreamEx.of(requestList).zipWith(responseList.stream())
.forKeyValue((request, response) ->
response.setPrimarySkills(request.getPrimarySkills()));
Upvotes: 0
Reputation: 53809
Using two iterators:
Iterator<Response> responseIt = responseList.iterator();
Iterator<Request> requestIt = requestList.iterator();
while(responseIt.hasNext() && requestIt.hasNext()) {
Response response = responseIt.next();
Request request = requestIt.next();
...
}
[Recommended for its clarity]
Using Guava Streams.forEachPair :
Streams.forEachPair(
requestList.stream(),
responseList.stream(),
(req, resp) -> resp.setPrimarySkills(req.getPrimarySkills())
);
Upvotes: 2
Reputation: 24527
You can use a for-loop with incrementing index:
List<String> l1 = List.of("a", "b");
List<Integer> l2 = List.of(1, 2);
for(int i=0; i<l1.size(); i++) {
String s = l1.get(i);
Integer i = l2.get(i);
}
Of course you should first make sure that both lists have equal length, to avoid OutOfBounds Exception.
Upvotes: 1
Reputation: 140299
Either, don't do it with a for-each loop, use an indexed for loop.
for (int i = 0; i < responseList.size(); ++i) {
responseList.get(i).setPrimarySkills(requestList.get(i).getPrimarySkills());
}
Or, use a pair of Iterator
s:
Iterator<Response> responseIt = responseList.iterator();
Iterator<Request> requestIt = requestList.iterator();
while (responseIt.hasNext() && requestIt.hasNext()) {
// Put responseIt.next() and requestIt.next() into variables, if you want.
responseIt.next().setPrimarySkills(requestIt.next().getPrimarySkills());
}
The advantage of Iterator
s over an index is that Iterator
s are efficient for non-RandomAccess
lists; but, unless your lists are big, it's unlikely to be a significant (or even noticable) difference.
You can do it with a for-each loop, by maintaining the index yourself, but it's a bit inconsistent in the treatment of the two lists:
int i = 0;
for (Response e : responseList) {
e.setPrimarySkills(requestList.get(i).getPrimarySkills());
i++;
}
Upvotes: 2