OldCurmudgeon
OldCurmudgeon

Reputation: 65851

Simplest way to turn a number of indexed items into a stream

Given a bunch of things that have a int size() method and a get(int i) method, how can it most easily be streamed?

import nu.xom.Builder;
import nu.xom.Element;
import nu.xom.Elements;

// My builder.
Builder builder = new Builder();

class Thing {
    public Thing(Element from) {
        // Construct from an Element.
    }
}

private Stream<Thing> allThings(Path path) throws FileNotFoundException, ParsingException, IOException {
    Elements things = builder.build(new FileInputStream(path.toFile()))
            .getRootElement().getChildElements();
    // Return a stream of `Thing`s created from all of the children.
    // How??
}

My attempt used an old-school Iterable and streamed that which seems unnecessarily messy.

Upvotes: 2

Views: 81

Answers (2)

Alexis C.
Alexis C.

Reputation: 93872

Looking at the Elements class, it seems it only have (as you said) get(int index) and size() so I think your simplest option is to use an IntStream followed by mapToObj:

private Stream<Thing> allThings(Path path) throws FileNotFoundException, ParsingException, IOException {
    Elements things = builder.build(new FileInputStream(path.toFile()))
            .getRootElement().getChildElements();
    return IntStream.range(0, things.size()).mapToObj(i -> new Thing(things.get(i)));
}

Upvotes: 1

assylias
assylias

Reputation: 328735

Maybe something like:

return IntStream.range(0, things.size())
          .mapToObj(things::get)
          .map(Thing::new);

Upvotes: 5

Related Questions