-2

I have an array of items, and I want to create a list (or any iterable) from an instance variable belonging to them.

public void foo(final MyClass... args) {
    final List<Baz> properties = new ArrayList<>();
    for (final MyClass a : args) {
        properties.add(a.getProperty());
    }
}

How would I do this using a one-liner stream?

Shyam Baitmangalkar
  • 1,075
  • 12
  • 18
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25

2 Answers2

3
List<Baz> list = Arrays.stream(args).map(MyClass::getProperty).collect(Collectors.toList());
Iterable<Baz> iterable = () -> Arrays.stream(args).map(MyClass::getProperty).iterator();
0

Assuming that getProperty() method of MyClass returns an object of type Baz

List<Baz> properties = Stream.of(args)
.map(myClazz -> myClazz.getProperty())
.collect(Collectors.toList())
Shyam Baitmangalkar
  • 1,075
  • 12
  • 18