Skip to content
Advertisement

How to modify an Array on Java using without use a nested for loop?

I’m using Java 8 and Groovy, unfortunately I can’t use lambdas and I have two different lists of objects with one attribute in common, on the first List I get the most of data I need and on the second list I get the data in common, I wrote a for nested loop in order to update the first list with the attribute in common from the second list, I just want to know if there is a better way to improve this code:

    List<Object1> firstList = dao.something();
    List<Object2> secondList = dao.something2();
    List<Object1> thirdList = new ArrayList<Object1>();

    for (Object1 obj1 : firstList){
        for(Object2 obj2 : secondList){
            if(obj1.getSomething().equals(obj2.getSomething())){
                    obj1.setAttribute(ojb2.getAttribute);
                    thirdList.add(obj1);
            }
        }
    }

Any help will be useful, thank you.

Advertisement

Answer

You can use Iterable’s forEach method to go through every element and search it in secondList and modify the content of the object

firstList.forEach(elem -> {
        V2 found = secondList.stream().filter(v1 -> v1.getId() == elem.getId()).findAny().orElse(null);               
        if(found != null) {
            elem.setAttribute(found);
        }
    });

Or you could use streams and map it into another list

 List<V1> thirdList = firstList.stream().map(elem -> { 
        V2 found = secondList.stream().filter(v1 -> v1.getId() == elem.getId()).findAny().orElse(null);               
        if(found != null) {
            elem.setAttribute(found);
        }
        return elem;
    }).collect(Collectors.toList());

If you want to compare two lists you’ll always need to iterate twice. I hope this is helpful for you.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement