1

So I am trying to count the number of objects in an ArrayList using just Stream. I am using stream.count but that is only returning 1 where as my list has more than 1 objects. Here is some code:

 static ArrayList<Person> people = new ArrayList<>();

  void loadCourses(){ // putting Person objects in the list }

  public void countPeople()
{
    Stream<ArrayList<Person>> stream1 = Stream.of(people); 
    long l = stream1.count();
    System.out.println("Number of people loaded: " + l);

}

Any help is appreciated :)

2 Answers 2

6

You are using a Stream<ArrayList<Person>> rather than a Stream<Person>.

You want:

long l = people.stream().count();

You are getting 1 because there is only one ArrayList.

Note also that you do not need streams for this. You can just do people.size().

Sign up to request clarification or add additional context in comments.

Comments

3

As an addition to @PaulBoddington answer: I strongly encourage you to use simply people.size(). In Java-8 when you do this using a stream like people.stream().count(), it actually iterates over the whole Collection. So this code effectively works like this:

long count = 0;
for(Person p : people) count++;
return count;

This could be enormously slow for big collections. In contrast people.size() just returns the value of the size field stored inside the ArrayList.

This problem is already fixed in Java-9 code (see JDK-8067969), but this fix is not backported to Java-8.

Comments

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.