Java streams 28. Collect 4. Counting stream elements

Collectors.counting() vs Stream.count() operation

  long c1 = Stream.of("cat", "fish", "dog")
System.out.print(c1); //prints: 3
  long c2 = Stream.of("cat", "fish", "dog").count();
System.out.print(c2); //prints: 3
  long c3 = Stream.of("cat", "fish", "dog")
.peek(s -> System.out.print(s)) //is not called
System.out.print(c3); //prints: 3
long c4 = Stream.of("cat", "fish", "dog")
.peek(s -> System.out.print(s)) //prints: catfishdog
System.out.print(c4); //prints: 3
  long c5 = Stream.of("cat", "fish", "dog")
.peek(s -> System.out.print(s)) //prints: cat
System.out.print(c5); //prints: 1
  long c7 = Stream.of("cat", "fish", "dog")
.peek(s -> System.out.print(s)) //prints: cat
System.out.print(c7); //prints: 1
  class Counter{
long count;
public void Count(){}
public void increment(){ this.count++; }
public long getCount(){ return this.count; }
Counter counter1 = new Counter();
long c9 = Stream.of("cat", "fish", "dog")
.peek(s -> counter1.increment()) //not called
System.out.print(c9); //prints:3
System.out.print(counter1.getCount()); //prints: 0
Counter counter2 = new Counter();
long c10 = Stream.of("cat", "fish", "dog")
.peek(s -> counter2.increment()) //prints: cat
System.out.print(c10); //prints: 3
System.out.print(counter2.getCount()); //prints: 3



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nick Samoylov

Nick Samoylov


Born in Moscow, lived in Crimea, now lives in the US. Used to be physicist and rock climber, now programmer and writer.