3

I have an object:

Trip {
        private TripName tripName;
        private List<TripStops> tripStops;
}

Trip Stops contains

TripStops {
           private PackageObject packageObject;
           private PackageTask packageTask;
}

I'm trying to get the count of PackageObject inside trip stop using Java8.

Will I be able to do something like this? Or is there a better way

Integer packageCount = Trip.getTripStops.stream().filter(TripStops::getPackageObject).count
0

1 Answer 1

4

To interpret the sentence "I'm trying to get the count of PackageObject inside trip stop" into code would be:

long count = Trip.getTripStops().stream().count();

or simply:

int count = Trip.getTripStops().size();

as each TripStops has one instance of PackageObject.

However, to get a count of the elements returned from TripStops::getPackageObject which pass a given criteria:

long count = Trip.getTripStops().stream()
                                .map(TripStops::getPackageObject)
                                .filter(criteria) // where criteria is the condition to be passed
                                .count();

// or merge map/filter into one with ---> .filter(t -> t.getPackageObject()...)
Sign up to request clarification or add additional context in comments.

1 Comment

@Buccaneer you’re more than welcome. As a way of saying “thank you” you could upvote the answer and mark it as accepted. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.