Vivek Goel
Vivek Goel

Reputation: 24150

Java 8 optional list

I am trying to achieve following: Given an list of object. Return starting 5 object which fulfill a criteria.

I am able to first element:

optionServiceObject.map((p) -> (List<ServiceAttribute>) p.getFoor())
                   .flatMap((v2) -> v2.stream().filter((v3) -> v3.hasBar())
                   .map(v3 -> v3.getBar())
                   .findFirst()

But unable to get, how to get starting 5 element matching the criteria into list.

Upvotes: 1

Views: 1269

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100209

If you want to get object number 5, skip the first four objects with skip(4):

Optional<Bar> fifthObject = optionServiceObject
                    .map((p) -> (List<ServiceAttribute>) p.getFoor())
                    .flatMap((v2) -> v2.stream().filter((v3) -> v3.hasBar())
                    .map(v3 -> v3.getBar())
                    .skip(4)
                    .findFirst();

The result will be empty if you have less than 5 matching objects.

If you want to get at most 5 matching objects, use limit(5) and collect the results to the List:

List<Bar> fiveObjects = optionServiceObject
                    .map((p) -> (List<ServiceAttribute>) p.getFoor())
                    .flatMap((v2) -> v2.stream().filter((v3) -> v3.hasBar())
                    .map(v3 -> v3.getBar())
                    .limit(5)
                    .collect(Collectors.toList());

Upvotes: 2

Related Questions