|
| 1 | +package com.hkbea.chap5; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Comparator; |
| 5 | +import java.util.List; |
| 6 | +import java.util.stream.Collectors; |
| 7 | + |
| 8 | +public class PuttingIntoPractice { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + Trader raoul = new Trader("Raoul", "Cambridge"); |
| 12 | + Trader mario = new Trader("Mario","Milan"); |
| 13 | + Trader alan = new Trader("Alan","Cambridge"); |
| 14 | + Trader brian = new Trader("Brian","Cambridge"); |
| 15 | + |
| 16 | + List<Transaction> transactions = Arrays.asList( |
| 17 | + new Transaction(brian, 2011, 300), |
| 18 | + new Transaction(raoul, 2012, 1000), |
| 19 | + new Transaction(raoul, 2011, 400), |
| 20 | + new Transaction(mario, 2012, 710), |
| 21 | + new Transaction(mario, 2012, 700), |
| 22 | + new Transaction(alan, 2012, 950) |
| 23 | + ); |
| 24 | + |
| 25 | + List<Transaction> tr2011 = transactions.stream().filter(t -> t.getYear() == 2011).sorted(Comparator.comparing(Transaction::getValue)).collect(Collectors.toList()); |
| 26 | + System.out.println(tr2011); |
| 27 | + |
| 28 | + List<String> citys = transactions.stream().map(t -> t.getTrader().getCity()).distinct().collect(Collectors.toList()); |
| 29 | + System.out.println(citys); |
| 30 | + |
| 31 | + List<Trader> traders = transactions.stream().map(Transaction::getTrader).distinct().filter(t -> "Cambridge".equals(t.getCity())).sorted(Comparator.comparing(Trader::getName)).collect(Collectors.toList()); |
| 32 | + System.out.println(traders); |
| 33 | + |
| 34 | + String traderStr = transactions.stream().map(t -> t.getTrader().getName()).distinct().sorted().reduce("", String::concat); |
| 35 | + System.out.println(traderStr); |
| 36 | + |
| 37 | + System.out.println(transactions.stream().anyMatch(t -> "Milan".equals(t.getTrader().getCity()))); |
| 38 | + |
| 39 | + transactions.stream().filter(t -> "Cambridge".equals(t.getTrader().getCity())).mapToInt(Transaction::getValue).forEach(System.out::println); |
| 40 | + |
| 41 | + transactions.stream().mapToInt(Transaction::getValue).reduce(Integer::max).ifPresent(System.out::println); |
| 42 | + |
| 43 | + transactions.stream().reduce((t1, t2) -> t1.getValue() < t2.getValue() ? t1:t2).ifPresent(System.out::println); |
| 44 | + |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments