Search code examples
javafor-loopnested-loopsaggregation

Using aggregates to replace nested for-loops


    for (Sample i : DATA) {
        for(Sample ii : DATA){

            if(i.getID() == ii.getID()){
                // Do nothing.
            }else {
                i.addMatch(new Match(ii.getID()));
            }
        }
    }

I have a List<Sample> and each Sample contains a List<Match>. List<Match> is a collection of Samples matched to another Sample. Thus, List<Match> contains all original samples minus the one they are being compared to.

Q1: Are aggregate operations useful here? If not, how can I know when they are?

Q2: If yes, what would be the appropriate way to write that?

EDIT: Java lesson on Aggregate Operations.


Solution

  • Q1: Are aggregate operations useful here? If not, how can I know when they are?

    They're partially useful in your case. If you want to iterate over a Collection it's always better to use the old-fashioned foreach loop because it doesn't have the overhead of creating a Stream pipeline. But your inner loop fits perfect for Stream processing because you filter and map every element.

    Q2: If yes, what would be the appropriate way to write that?

    for (Sample sample : DATA) {
        DATA.stream()
           .mapToInt(Sample::getId).filter(id -> id != sample.getId()).mapToObj(Match::new)
           .forEach(m -> sample.addMatch(m));
    }