javalistjava-streammodelmapper

Iterate over one collection and get the same index value of another collection


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 ?


Solution

  • 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())
    );