Skip to content

Instantly share code, notes, and snippets.

View SilverioMG's full-sized avatar

Silverio Martinez Garcia SilverioMG

View GitHub Profile
@Test
public void max() {
Book book = bookList.stream()
.max((book1, book2) -> {
return (book1.getPrice().compareTo(book2.getPrice()));
})
.orElse(null);
System.out.println(book);
assertEquals(book.getPrice(), 50.99);
@Test
public void min() {
Book book = bookList.stream()
.min((book1, book2) -> book1.getPrice().compareTo(book2.getPrice()))
.orElse(null);
System.out.println(book);
assertEquals(book.getPrice(), 10);
}
@Test
public void sorted() {
List<Book> books = bookList.stream()
.sorted((book1, book2) -> book1.getAuthor().compareToIgnoreCase(book2.getAuthor()))
.peek(System.out::println)
.collect(Collectors.toList());
assertTrue(books.get(0).getAuthor().contains("Bartolomé"));
assertTrue(books.get(1).getAuthor().contains("José"));
assertTrue(books.get(2).getAuthor().contains("Luís"));
@Test
public void toArray() {
//Como se hacía antes de los Streams (2 formas distintas):
Book[] booksArray = bookList.toArray(Book[]::new);
booksArray = bookList.toArray(new Book[bookList.size()]);
//Como se hace con Streams (sirve para cualquier tipo de 'Collection', no solo para listas):
booksArray = bookList.stream().toArray(Book[]::new);
//Convertimos el array en un stream para visualizar su contenido más fácilmente sin tener que utilizar el 'for(Book book: booksArray)' de toda la vida:
@Test
public void findFirst() {
Book bookFirst = bookList.stream()
.filter(book -> book.getPrice() >= 15)
.peek(System.out::println)
.findFirst()
.orElse(null);
assertTrue(bookFirst.getPrice() >= 15);
}
@Test
public void filter() {
List<Book> books = bookList.stream()
.filter(book -> book.getPrice() >= 15)
.peek(book -> System.out.println(book))
.collect(Collectors.toList());
assertTrue(books.size() == 2);
}
@Test
public void mapAndForEach() {
List<String> titles = bookList.stream()
.map(book -> book.getTitle())
.peek(title -> System.out.println(title))
.collect(Collectors.toList());
assertEquals(titles.size(), bookList.size());
bookList.forEach(
(book) -> {
@Test
public void forEach() {
bookList.stream()
.forEach(book -> {
double newPrice = book.getPrice();
newPrice *= 2;
book.setPrice(newPrice);
System.out.println(book);
});
}
@Test
public void map() {
List<String> titles = bookList.stream()
.map(book -> book.getTitle())
.peek(title -> System.out.println(title))
.collect(Collectors.toList());
assertEquals(titles.size(), bookList.size());
}
@Test
public void peek() {
List<Book> books = bookList.stream()
.peek(book -> book.setAuthor("ATopeCode"))
.peek(book -> System.out.println(book))
.collect(Collectors.toList());
}