Casos prácticos de uso de Stream en Java
![](https://rubentejera.com/wp-content/uploads/15052015-_MG_7221-1024x683.jpg)
Resultados:
-----VALUES----->
ID:1 NAME:Ruben AGE:18
ID:2 NAME:Pepe AGE:35
ID:3 NAME:Juan AGE:34
ID:4 NAME:Ruben AGE:32
ID:5 NAME:Antonio AGE:32
-----1.-FILTER-----> Example findByAge
ID:4 NAME:Ruben AGE:32
ID:5 NAME:Antonio AGE:32
-----2.-MAP-----> Example getAllAges
18
35
34
32
32
-----3.-SORTED-----> Example getListOfNamesSorted
Antonio
Juan
Pepe
Ruben
Ruben
-----4.-ANYMATCH----->
-----4.1-ANYMATCH-----> Example isThereAUsernameThatStartsWithTheLetter
true
-----4.2-ALLMATCH-----> Example doAllUsernamesStartWithALetter
false
-----4.3-ANYMATCH-----> Example doAnyUsernamesStartWithTheLetter
false
-----5.-SKIP-----> Example getAllUsersSkipping
ID:3 NAME:Juan AGE:34
ID:4 NAME:Ruben AGE:32
ID:5 NAME:Antonio AGE:32
-----6.-LIMIT-----> Example getAllUsersLimitedTo
ID:1 NAME:Ruben AGE:18
ID:2 NAME:Pepe AGE:35
-----7.-PAGINATION-----> Example getUsersPagination
ID:5 NAME:Antonio AGE:32
-----8.-COLLECTORS.GROUPINGBY-----> Example getGroupsOfUsersByAges
KEY:32
ID:4 NAME:Ruben AGE:32
ID:5 NAME:Antonio AGE:32
KEY:34
ID:3 NAME:Juan AGE:34
KEY:18
ID:1 NAME:Ruben AGE:18
KEY:35
ID:2 NAME:Pepe AGE:35
-----9.-COLLECTORS.COUNTING-----> Example getNumberOfUsersByAges
KEY:32 VALUE:2
KEY:34 VALUE:1
KEY:18 VALUE:1
KEY:35 VALUE:1
-----10.-COLLECTORS.SUMMING-----> Example getUsersNamesAndTheSumOfAges
KEY:Ruben VALUE:50
KEY:Juan VALUE:34
KEY:Antonio VALUE:32
KEY:Pepe VALUE:35
-----11.-COLLECTORS.SUMMARIZING-----> Example getStatisticsOfAge
DoubleSummaryStatistics{count=5, sum=151,000000, min=18,000000, average=30,200000, max=35,000000}
-----12.-REDUCE-----> Example getSumOfAge
151
Codigo:
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
System.out.println("-----VALUES-----> ");
printUsers(findAll());
System.out.println("-----1.-FILTER-----> Example findByAge");
printUsers(findByAge(32));
System.out.println("-----2.-MAP-----> Example getAllAges");
printList(getAllAges());
System.out.println("-----3.-SORTED-----> Example getListOfNamesSorted");
printList(getListOfNamesSorted());
System.out.println("-----4.-ANYMATCH----->");
System.out.println("-----4.1-ANYMATCH-----> Example isThereAUsernameThatStartsWithTheLetter");
System.out.println(isThereAUsernameThatStartsWithTheLetter("R")+"\n");;
System.out.println("-----4.2-ALLMATCH-----> Example doAllUsernamesStartWithALetter");
System.out.println(doAllUsernamesStartWithALetter("R")+"\n");;
System.out.println("-----4.3-ANYMATCH-----> Example doAnyUsernamesStartWithTheLetter");
System.out.println(doAnyUsernamesStartWithTheLetter("R")+"\n");;
System.out.println("-----5.-SKIP-----> Example getAllUsersSkipping");
printUsers(getAllUsersSkipping(2));;
System.out.println("-----6.-LIMIT-----> Example getAllUsersLimitedTo");
printUsers(getAllUsersLimitedTo(2));;
System.out.println("-----7.-PAGINATION-----> Example getUsersPagination");
printUsers(getUsersPagination(2,2));;
System.out.println("-----8.-COLLECTORS.GROUPINGBY-----> Example getGroupsOfUsersByAges");
printUsersMap(getGroupsOfUsersByAges());;
System.out.println("-----9.-COLLECTORS.COUNTING-----> Example getNumberOfUsersByAges");
printMap(getNumberOfUsersByAges());;
System.out.println("-----10.-COLLECTORS.SUMMING-----> Example getUsersNamesAndTheSumOfAges");
printMap(getUsersNamesAndTheSumOfAges());;
System.out.println("-----11.-COLLECTORS.SUMMARIZING-----> Example getStatisticsOfAge");
System.out.println(getStatisticsOfAge()+"\n");
System.out.println("-----12.-REDUCE-----> Example getSumOfAge");
System.out.println(getSumOfAge().get()+"\n");
}
public static List<User> findAll() {
List<User> users;
users = new ArrayList<User>();
users.add(new User(1, "Ruben", 18));
users.add(new User(2, "Pepe", 35));
users.add(new User(3, "Juan", 34));
users.add(new User(4, "Ruben", 32));
users.add(new User(5, "Antonio", 32));
return users;
}
//1.- Filter (param:Predicate)
public static List<User> findByAge(int age) {
//FILTER (Param:Predicate)
// El filtro espera un valor booleano
// El filtro devuelve una lista del mismo tipo que la que estamos recorriendo.
List<User> users = findAll();
users = users.stream()
.filter(user -> user.getAge() == age)
.collect(Collectors.toList());
return users;
}
//2.-MAP (param:Function)
public static List<Integer> getAllAges() {
//MAP (param:Function)
// El filtro espera un valor que retorne de la funcion de cualquier tipo.
// El map devuelve una lista del tipo que devuelva la funcion que ataquemos.
List<User> users = findAll();
List<Integer> ages = new ArrayList<>();
return users.stream()
.map(User::getAge)
.collect(Collectors.toList());
}
//3.- SORTED (param:Comparator)
public static List<String> getListOfNamesSorted() {
// Comparator<User> byNameAsc = (User user1, User user2) -> user1.getName().compareTo(user2.getName());
Comparator<User> byNameAsc = Comparator.comparing(User::getName);
Comparator<User> byNameDesc = Comparator.comparing(User::getName).reversed();
List<User> users = findAll();
return users.stream()
.sorted(byNameAsc)
.map(user -> user.getName())
.collect(Collectors.toList());
}
//4.- Match (param:Predicate)
//Create a Predicate to practice
Predicate<User> startsWithRPredicate = user -> user.getName().startsWith("R");
//4.1.- anyMatch: No evalua el stream completo, termina en la primera coincidencia
// Using Predicate
public static boolean isThereAUsernameThatStartsWithTheLetter(String letter) {
List<User> users = findAll();
return users.stream()
.anyMatch(user -> user.getName().startsWith(letter));
// .anyMatch(startsWithRPredicate);
}
//4.2.- allMatch: Evalua el stream completo bajo la condicion
public static boolean doAllUsernamesStartWithALetter(String letter) {
List<User> users = findAll();
return users.stream()
.allMatch(user -> user.getName().startsWith(letter));
}
//4.3.- noneMatch: Evalua el stream completo bajo la condicion
public static boolean doAnyUsernamesStartWithTheLetter(String letter) {
List<User> users = findAll();
return users.stream()
.noneMatch(user -> user.getName().startsWith(letter));
}
//5.- Skip
public static List<User> getAllUsersSkipping(int numberOfSkip) {
List<User> users = findAll();
return users.stream()
.skip(numberOfSkip)
.collect(Collectors.toList());
}
//6.- Limit
public static List<User> getAllUsersLimitedTo(int numberOfLimit) {
List<User> users = findAll();
return users.stream()
.limit(numberOfLimit)
.collect(Collectors.toList());
}
//7.- Pagination (Limit/Skip)
public static List<User> getUsersPagination(int pageNumber, int pageSize) {
List<User> users = findAll();
return users.stream()
.skip(pageNumber * pageSize)
.limit(pageSize)
.collect(Collectors.toList());
}
//8.-COLLECTORS.GROUPINGBY
public static Map<Integer, List<User>> getGroupsOfUsersByAges() {
List<User> users = findAll();
return users.stream()
.collect(Collectors.groupingBy(User::getAge));
}
//9.- COLLECTORS.COUNTING
public static Map<Integer, Long> getNumberOfUsersByAges() {
List<User> users = findAll();
return users.stream()
.collect(Collectors.groupingBy(
User::getAge, Collectors.counting()
)
);
}
//10.-COLLECTORS.SUMMING
public static Map<String, Integer> getUsersNamesAndTheSumOfAges() {
List<User> users = findAll();
return users.stream()
.collect(Collectors.groupingBy(
User::getName, Collectors.summingInt(User::getAge)
)
);
}
//11.-COLLECTORS.SUMMARIZING
public static DoubleSummaryStatistics getStatisticsOfAge() {
List<User> users = findAll();
return users.stream()
.collect(Collectors.summarizingDouble(User::getAge));
}
//12.-REDUCE
public static Optional<Integer> getSumOfAge() {
List<User> users = findAll();
return users.stream()
.map(User::getAge)
.reduce(Integer::sum);
}
public static void printUsers(List<User> users) {
for (User user : users
) {
System.out.println("ID:" + user.getId() + " NAME:" + user.getName() + " AGE:" + user.getAge());
}
System.out.println();
}
public static void printList(List<?> elements) {
for (Object element : elements
) {
System.out.println(element);
}
System.out.println();
}
public static void printMap(Map<?, ?> elements) {
elements.forEach(
(key, value) -> {
System.out.println("KEY:"+key+" VALUE:"+value);
});
System.out.println();
}
public static void printUsersMap(Map<Integer, List<User>> elements) {
elements.forEach(
(key, users) -> {
System.out.println("KEY:"+key);
printUsers(users);
});
}
}
class User {
private String name;
private int age;
private int id;
public User(int id, String name, int age) {
this.name = name;
this.age = age;
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}