1

I have two lists first List<ClassOne> and second List<ClassTwo>. ClassOne has the following fields:

ClassOne:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class ClassOne {
    private Integer idToInsert;
    private String fieldToCompare;
    private List<AnotherClass> anotherClass;
}

And ClassTwo has the following fields:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class ClassTwo {

    private Integer idToInsert;
    private String fieldToCompare;

}

And I have this two Lists List<ClassOne> and List<ClassTwo>. ClassTwo contains the idToInsert field, which must be inserted in ClassOne, when the fieldToCompare field is the same in both classes.

Something like

if(classtwo.getFieldToCompare.equals(classOne.getFieldTocompare){
  classOne.setIdToInsert(classTwo.getIdToInsert());
}

How can I do this comparing this two lists?

1 Answer 1

1

I will suggest to collect List<ClassTwo> into Map<String,Integer> which is Map(fieldToCompare, idToInsert) for better performance

Map<String,Integer> classTwoMap = classTwoList.stream()
                    .collect(Collectors.toMap(two->two.getFieldToCompare(), two->two.getIdToInsert()));

And then now just use forEach on classListOne

classListOne.forEach(one -> one.setidToInsert(classTwoMap.getOrDefault(one.getFieldTocompare(),one.getIdToInsert())));
   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.