cbwrk
cbwrk

Reputation: 1

Does Java offer a way to iterate over a number of individual objects?

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

Answers (3)

Damith
Damith

Reputation: 747

use arrays

Object[] arr = new Object[]{o1, o2, o3};
for (Object o : arr) {
  doSomething();
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

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

Live Example

Upvotes: 3

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Java8 introduces the Stream API, with which we're able to do:

Stream.of(o1, o2, o3).forEach(() -> doSomething());

Upvotes: 3

Related Questions