Bazuka
Bazuka

Reputation: 417

Nested for loop in handling files - java 8

I want to write for inside for in java 8:

for (String file : files) {
                for (String line : lines) {
                    if (file.contains(line)) {
                       //do something
                    }
                }
            }

I don't want to write for each inside for each like:

files.stream().forEach(file -> { 
      lines.stream().forEach(line-> {
        //do something
      })
})

is there anything like

(file, line) -> { //do something}

and inside the pair I will get all possible permutations

Upvotes: 2

Views: 330

Answers (2)

AxelH
AxelH

Reputation: 14572

Or you can simply defined a class that will hold one of the list to do the research in a method taking a String. I used a Dictionary class for the example here to find every "word" define in another list.

public class Dictionary{

    private List<String> list;

    public Dictionary(List<String> list){
        this.list = list;
    }

    public void printMatch(String word){
        list.stream().filter(word::contains).forEach(System.out::println);
    }
}

Then, for each file, just call the method.

public static void main(String[] args) {
    Dictionary d = new Dictionary(Arrays.asList("abc", "def", "fgh"));
    Stream.of("def", "ijk").forEach(d::printMatch);
}

The example is not suppose to match the actual requirement but to show a simple solution to not use inner loops directly (simply by hiding them in a method ;) ).

Upvotes: 1

Eugene
Eugene

Reputation: 121028

You could something like this, but it isn't much different from what you already have in place

 files.stream()
      .flatMap(file -> lines.stream().map(line -> new Pair(file, line)))
      .map(pair -> do something with pair)

Upvotes: 7

Related Questions