Reputation: 1
I have a couple of objects on which I want to perform the same operations, however they are not currently grouped into a collection or array. Does java offer a way to implicitly generate something I can iterate over?
I'm thinking of a syntax like
Object o1, o2, o3;
for (Object o : {o1, o2, o3}) {
doSomething();
}
I'm currently using
Object o1, o2, o3;
for (Object o : Arrays.asList(o1, o2, o3)) {
doSomething();
}
which is obviously quite neat already, but I figured there might be a built-in way I just haven't found.
Regarding answers to create an Array, List or similar: as you can see from my example I already do that, my question is aimed at whether this can be shortened any more or not. So more of an academical question about syntax and language capabilities than about programming technique.
Upvotes: 0
Views: 53
Reputation: 747
Object[] arr = new Object[]{o1, o2, o3};
for (Object o : arr) {
doSomething();
}
Upvotes: 1
Reputation: 1074989
You're close with your first example, you just have to tell it what those {}
are for:
for (Object o : new Object[] {o1, o2, o3}) {
doSomething();
}
Upvotes: 3
Reputation: 62864
Java8 introduces the Stream API, with which we're able to do:
Stream.of(o1, o2, o3).forEach(() -> doSomething());
Upvotes: 3