简体   繁体   中英

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.

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));
}

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