简体   繁体   中英

How to iterate two lists simultaneously using Java 8

I below two lists

List<Map<String, Strings>> mapList
List<MyObject> myObjectList

Both lists have same size.

Currently I am iterating them using for loop as below.

List <CustomObject> customObjectList1 = new ArrayList();

List <CustomObject> customObjectList2 = new ArrayList();

int i=0;
for(MyObject myObject:myObjectList){
   if(“NEW”.equalIgnoreCase(myObject.getType)){
       customObjectList1.add(constructCustomObject(myObject, mapList.get(i));
   }
   if(“DELETE”.equalIgnoreCase(myObject.getType)){
       customObjectList2.add(constructCustomObject(myObject, mapList.get(i));
   }
   i++;
}
if(!customObjectList1.isEmpty()){
   jpaRepo.saveAll(customObjectList1);
}
if(!customObjectList2.isEmpty()){
   jpaRepo.deleteAll(customObjectList2);
}

Any better/efficient way to iterate two lists simultaneously using Java 8?

Seems like your issue centers in the ability of knowing the index of the object you are iterating on.

If you want to do it the stream way, maybe you can try something like this

Disclaimer : I do not think it will have a very big impact on performance since there are no objects that can be released by the GC, or decrease in number of iterations.

IntStream.range(0, myObjectList.size())
  .forEach(idx -> {
     MyObject myObject = myObjectList.get(idx);
     if(“NEW”.equalIgnoreCase(myObject.getType)){
       customObjectList1.add(constructCustomObject(myObject, mapList.get(idx));
     }
     if(“DELETE”.equalIgnoreCase(myObject.getType)){
       customObjectList2.add(constructCustomObject(myObject, mapList.get(idx));
     }
  });
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM