public class Trader {
private final String name;
private final String city;
public Trader(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
@Override
public String toString() {
return "Trader{" + "name='" + name + '\'' + ", city='" + city + '\'' + '}';
}
}
public class Transaction {
private final Trader trader;
private final int year;
private final int value;
public Transaction(Trader trader, int year, int value) {
this.trader = trader;
this.year = year;
this.value = value;
}
@Override
public String toString() {
return "Transaction{" + "trader=" + trader + ", year=" + year + ", value=" + value + '}';
}
public Trader getTrader() {
return trader;
}
public int getYear() {
return year;
}
public int getValue() {
return value;
}
}
public void test() {
Trader raoul = new Trader("Raoul", "Cambridge");
Trader mario = new Trader("Mario", "Milan");
Trader alan = new Trader("Alan", "Cambridge");
Trader brian = new Trader("Brian", "Cambridge");
List<Transaction> transactions =
Arrays.asList(
new Transaction(brian, 2011, 300),
new Transaction(raoul, 2012, 1000),
new Transaction(raoul, 2011, 400),
new Transaction(mario, 2012, 710),
new Transaction(mario, 2012, 700),
new Transaction(alan, 2012, 950));
// (1) 找出2011年發生的所有交易,並按交易額排序(從低到高)
transactions.stream()
.filter(transaction -> transaction.getYear() == 2012)
.sorted(Comparator.comparing(Transaction::getValue))
.collect(Collectors.toList());
// (2) 交易員都在哪些不同的城市工作過
transactions.stream()
.map(transaction -> transaction.getTrader().getCity())
.distinct()
.collect(Collectors.toList());
// (3) 查找所以來自於劍橋的交易員,並按照姓名順序排序
transactions.stream()
.map(Transaction::getTrader)
.filter(trader -> "Cambridge".equals(trader.getCity()))
.distinct()
.sorted(Comparator.comparing(Trader::getName))
.collect(Collectors.toList());
// (4) 返回所有交易員的姓名字符串,並按照字母排序
transactions.stream()
.map(transaction -> transaction.getTrader().getName())
.distinct()
.sorted()
.collect(Collectors.joining());
// (5) 打印生活在劍橋的交易員的所有交易額
transactions.stream()
.filter(transaction -> transaction.getTrader().getName().equals("Cambridge"))
.forEach(transaction -> System.out.println(transaction.getValue()));
// (6) 有沒有交易員是在米蘭工作的
boolean milanBased =
transactions.stream()
.anyMatch(transaction -> transaction.getTrader().getName().equals("Milan"));
// (7) 所有交易中,最高的交易額是多少
Optional<Integer> highestValue =
transactions.stream().map(Transaction::getValue).reduce(Integer::max);
// (8) 找到交易額最小的交易
transactions.stream()
.reduce((a, b) -> a.getValue() > b.getValue() ? b : a)
.ifPresent(transaction -> System.out.println(transaction.getValue()));
}
參考書籍:Java8實戰