-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?

4
  • So an instance of MyClass has a property of type MyClass? Am I getting this right? Commented Jul 2, 2020 at 12:20
  • 3
    java.util.List has no append method. Commented Jul 2, 2020 at 12:21
  • 1
    Fixed both, wrote this without compiling it and I jump between programming languages Commented Jul 2, 2020 at 12:24
  • Arrays.stream(args).map(MyClass::getProperty).collect(Colectors.toList()); ? Commented Jul 2, 2020 at 12:30

2 Answers 2

3
List<Baz> list = Arrays.stream(args).map(MyClass::getProperty).collect(Collectors.toList());
Iterable<Baz> iterable = () -> Arrays.stream(args).map(MyClass::getProperty).iterator();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.