简体   繁体   中英

Count number of objects in a list using Java8 Stream

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM