alexx
alexx

Reputation: 91

how to condense several foreach into a single for-each?

I want to concatenate each of these arrays, and then just iterate over the resulting collection.

        String[] type = {"school", "home"};
        String[] place = {"tokyo ", " New York"};
        String[] date = {"Sep", "Feb"};


        for(String name: type) {
            Assert.assertFalse(isValid(name));
        }
        for(String name: place) {
            Assert.assertFalse(isValid(name));
        }
        for(String name: date) {
            Assert.assertFalse(isValid(name));
        }

Upvotes: 2

Views: 176

Answers (2)

Pshemo
Pshemo

Reputation: 124275

Not necessarily for-each you showed but maybe you would be interested in something like:

Stream.of(type, place, date) //Stream<String[]> example [ [a,b], [c,d] ]
      .flatMap(Stream::of)   //Stream<String>   example [ a, b, c, d ]
      .forEach(name -> Assert.assertFalse(isValid(name));

which is similar to

for (String[] arr : Arrays.asList(type,place,date)){
    for(String name : arr){
        Assert.assertFalse(isValid(name)
    }
}

Upvotes: 2

Amerousful
Amerousful

Reputation: 2555

String[] type = {"school", "home"};
String[] place = {"tokyo ", " New York"};
String[] date = {"Sep", "Feb"};

        Arrays.asList(type, place, date).forEach(item -> {
            for (int i = 0; i < item.length; i++) {
                Assert.assertFalse(isValid(item[i]));
            }
        });

Upvotes: 0

Related Questions