Reputation: 75
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 :)
Upvotes: 1
Views: 4217
Reputation: 100199
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.
Upvotes: 3
Reputation: 37645
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()
.
Upvotes: 6