The count
method of the Stream
class is used to count the total element in the Stream
result. It's a terminal
operation.
package org.wesome.java8;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
class Apple {
public static void main(String args[]) {
/*-------------------------count on String-------------------------*/
List<String> apples = Arrays.asList("Macintosh", "Fuji", "Gala", "Jonagold");
long count = apples.stream().count();
System.out.println("max = " + count);
count = apples.stream().filter(str -> str.length() > 4).count();
System.out.println("max = " + count);
/*-------------------------count on int-------------------------*/
count = IntStream.rangeClosed(1, 5).count();
System.out.println("max = " + count);
count = IntStream.rangeClosed(1, 5).filter(ints -> ints % 2 == 0).count();
System.out.println("max = " + count);
}
}
Count on user-defined class.
package org.wesome.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
@Data
@AllArgsConstructor
class Fruit {
int fruitId;
String fruitName;
String taste;
double price;
}
class Apple {
public static void main(String args[]) {
List<Fruit> fruits = Arrays.asList(new Fruit(1, "Macintosh", "sweet", 1.1), new Fruit(2, "Fuji", "sweet", 2.2), new Fruit(3, "Gala", "sour", 1.1), new Fruit(4, "Jonagold", "sour", 2.2));
long count = fruits.stream().count();
System.out.println("count = " + count);
count = fruits.stream().filter(apple -> apple.getFruitId() % 2 == 0).count();
System.out.println("count = " + count);
}
}