Search code examples
javajava-streamnested-loops

Is it possible to replace nested loops on different collections with Stream API


I was wondering if it's possible to rewrite nested for loops using java.utils.stream in Java 8?

Here is a sample data type I'm working with:

class Folder {
  private final String name;
  private final Integer itemCound;

  Folder(String name, Integer itemCount) {
    this.name = name;
    this.itemCount = itemCount;
  }

  public String getName() { return this.name; }
  public Integer getItemCount() { return this.itemCount; }
}

Here's code in action:

List<Folder> oldFolders = new ArrayList<>();
List<Folder> newFolders = new ArrayList<>();

// Fill folder collections with sample data...
oldFolders.add(new Folder("folder1", 2));
oldFolders.add(new Folder("folder2", 4));
newFolders.add(new Folder("folder1", 0));
newFolders.add(new Folder("folder2", 100));

// This part should be rewrited using streams
for (Folder newFolder : newFolders) {
  for (Folder oldFolder : oldFolders) {
    if (newFolder.getName().equals(oldFolder.getName()) 
        && !newFolder.getItemCount().equals(oldFolder.getItemCount())) {
      // do stuff...    
    }
  }
}

P.S: I've seen other questions on SO, but all of them had 1 collection or a collection with it's own nested collection instead of two different collections like in my example.

Thanks in advance!


Solution

  • That not much of an improvement to be fair unless if you can parallelize the first iteration (commented in this example)

    List<String> oldList = new ArrayList<>();
    List<String> newList = new ArrayList<>();
    
    oldList
        //.stream()
        //.parallel() 
        .forEach(s1 ->
        newList
            .stream()
            .filter(s2 -> s1.equals(s2)) //could become a parameter Predicate
            .forEach(System.out::println) //could become a parameter Consumer
    );
    

    Replacing the if with a filter and his Predicate then executing a method on it.

    This would give a solution that can be dynamic providing different Predicate and Consumer to the filter and forEach method. That would be the only reason to work on this conversion.