Skip to content

Instantly share code, notes, and snippets.

@cleuton
Created November 12, 2019 16:38
Show Gist options
  • Save cleuton/8512ad67a773d714d48776a76558b262 to your computer and use it in GitHub Desktop.
Save cleuton/8512ad67a773d714d48776a76558b262 to your computer and use it in GitHub Desktop.
New stream API samples
package com.obomprogramador.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamDemo2 {
static class Order {
private Client client;
private double value;
private boolean delivered;
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public boolean isDelivered() {
return delivered;
}
public void setDelivered(boolean delivered) {
this.delivered = delivered;
}
public Order(Client client, double d, boolean b) {
this.client = client;
this.value = d;
this.delivered = b;
}
}
static class Client {
private String name;
private String address;
private List<Order> orders;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
Client (String name, String address) {
this.name = name;
this.address = address;
this.orders = new ArrayList<Order>();
}
}
public static void main (String [] args) {
Client client = new Client("John Doe", "145, 5th st");
client.getOrders().add(new Order(client, 100.50, true));
client.getOrders().add(new Order(client, 210.00, false));
// Find all non-delivered orders and print their value
// 1 - Procedural way:
for (Order order : client.getOrders()) {
if (!order.isDelivered()) {
System.out.println(order.value);
}
}
// 2 - Functional way:
System.out.println(client.getOrders().stream().filter(o -> !o.isDelivered()).map(o -> o.value).collect(Collectors.toList()));
// 3 - Using forEach:
client.getOrders().forEach(o -> {if (!o.isDelivered()) {System.out.println(o.getValue());}});
// 4 - Using double collon operator:
client.getOrders().stream().filter(o -> !o.isDelivered()).map(o -> o.value).forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment