Stream API练习
交易员类
public class Trader {
private String name;
private String city;
}
交易详情类
public class Transaction {
private Trader trader;
private Integer year;
private Integer value;
}
练习
public class TestTransaction {
List<Transaction> transactions =null;
@Before
public void before(){
Trader raoul = new Trader("Raoul","Cambridge");
Trader mario = new Trader("Mario","Milan");
Trader alan = new Trader("Alan","Cambridge");
Trader brain = new Trader("Brain","Cambridge");
transactions = Arrays.asList(
new Transaction(brain,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)
);
}
@Test
public void test1(){
transactions.stream()
.filter((t) -> t.getYear() == 2012)
.sorted((t1, t2) -> Integer.compare(t1.getValue(),t2.getValue()))
.forEach(System.out::println);
}
@Test
public void test2(){
transactions.stream()
.map((t) -> t.getTrader().getCity())
.distinct()
.forEach(System.out::println);
}
@Test
public void test3(){
transactions.stream()
.filter((t) -> t.getTrader().getCity().equals("Cambridge"))
.sorted((t1, t2) -> t1.getTrader().getName().compareTo(t2.getTrader().getName()))
.forEach(System.out::println);
}
@Test
public void test4(){
transactions.stream()
.map((t) -> t.getTrader().getName())
.distinct()
.sorted()
.forEach(System.out::println);
}
@Test
public void test5(){
boolean b = transactions.stream()
.anyMatch((t) -> t.getTrader().getCity().equals("Milan"));
System.out.println(b);
}
@Test
public void test6(){
Optional<Integer> first = transactions.stream()
.map(Transaction::getValue)
.max(Integer::compareTo);
System.out.println(first.get());
Optional<Integer> max = transactions.stream()
.map(Transaction::getValue)
.collect(Collectors.maxBy(Integer::compareTo));
System.out.println(max.get());
}
@Test
public void test7(){
Optional<Integer> sum = transactions.stream()
.filter((t) -> t.getTrader().getCity().equals("Cambridge"))
.map(Transaction::getValue)
.reduce(Integer::sum);
System.out.println(sum.get());
}
@Test
public void test8(){
Optional<Transaction> min = transactions.stream()
.min((t1, t2) -> Integer.compare(t1.getValue(), t2.getValue()));
System.out.println(min.get());
}
}