Stream初体验

最近在看《Java 8 in Action》,动手做了下5.5节的题目,Stream果然是一把利器,是时候升级到Java 8了。

题目:

1. Find all transactions in the year 2011 and sort them by value (small to high).
2. What are all the unique cities where the traders work?
3. Find all traders from Cambridge and sort them by name.
4. Return a string of all traders’ names sorted alphabetically.
5. Are any traders based in Milan?
6. Print all transactions’ values from the traders living in Cambridge.
7. What’s the highest value of all the transactions?
8. Find the transaction with the smallest value.

代码:

package java8.ch_five;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    /**
     * 答(非标准答案)
     * @param args
     */
    public static void main(String[] args) {
        List<Transaction> transactions = buildDomains();
        
        //1. Find all transactions in the year 2011 and sort them by value (small to high).
        List<Transaction> list1 = transactions.stream()
                    .filter(t -> t.getYear() == 2011)
                    .sorted((t1, t2) -> t1.getValue() - t2.getValue())
                    .collect(Collectors.toList());
        //2. What are all the unique cities where the traders work?
        List<String> list2 = transactions.stream()
                    .map(Transaction::getTrader)
                    .map(Trader::getCity)
                    .distinct()
                    .collect(Collectors.toList());
        //3. Find all traders from Cambridge and sort them by name.
        List<Trader> list3 = transactions.stream()
                    .map(Transaction::getTrader)
                    .filter(t -> t.getCity().equals("Cambridge"))
                    .sorted((t1, t2) -> t1.getName().compareTo(t2.getName()))
                    .collect(Collectors.toList());
        //4. Return a string of all traders’ names sorted alphabetically.
        String allTradersName = transactions.stream()
                    .map(Transaction::getTrader)
                    .map(Trader::getName)
                    .sorted()
                    .reduce((a, b) -> a + "-" + b)
                    .orElse("");
        //5. Are any traders based in Milan?
        boolean hasTraderInMilan = transactions.stream()
                    .anyMatch(t -> t.getTrader().getCity().equals("Milan"));
        //6. Print all transactions’ values from the traders living in Cambridge.
        List<Integer> list6 = transactions.stream()
                    .filter(t -> t.getTrader().getCity().equals("Cambridge"))
                    .map(Transaction::getValue)
                    .collect(Collectors.toList());
        //7. What’s the highest value of all the transactions?
        Integer maxValue = transactions.stream()
                    .map(Transaction::getValue)
                    .reduce(Integer::max)
                    .get();
        //8. Find the transaction with the smallest value.
        Transaction transaction = transactions.stream()
                    .reduce((a,b) -> a.getValue() < b.getValue() ? a : b)
                    .get();
        
        System.out.println(list1);
        System.out.println(list2);
        System.out.println(list3);
        System.out.println(allTradersName);
        System.out.println(hasTraderInMilan);
        System.out.println(list6);
        System.out.println(maxValue);
        System.out.println(transaction);
    }
    
    /**
     * 标准答案
     */
    public static void standardAnswer() {
        List<Transaction> transactions = buildDomains();
        
        //1. Find all transactions in the year 2011 and sort them by value (small to high).
        List<Transaction> list1 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                .sorted(Comparator.comparing(Transaction::getValue))
                .collect(Collectors.toList());
        //2. What are all the unique cities where the traders work?
        List<String> list2 = transactions.stream()
                .map(t -> t.getTrader().getCity())
                .distinct()
                .collect(Collectors.toList());
        //3. Find all traders from Cambridge and sort them by name.
        List<Trader> list3 = transactions.stream()
                .map(Transaction::getTrader)
                .filter(t -> t.getCity().equals("Cambridge"))
                .distinct()
                .sorted(Comparator.comparing(Trader::getName))
                .collect(Collectors.toList());
        //4. Return a string of all traders’ names sorted alphabetically.
        String allTradersName = transactions.stream()
                .map(t -> t.getTrader().getName())
                .sorted()
                .reduce("", (a, b) -> a + b);
        //5. Are any traders based in Milan?
        boolean hasTraderInMilan = transactions.stream()
                .anyMatch(t -> t.getTrader().getCity().equals("Milan"));
        //6. Print all transactions’ values from the traders living in Cambridge.
        transactions.stream()
                .filter(t -> t.getTrader().getCity().equals("Cambridge"))
                .map(Transaction::getValue)
                .forEach(System.out::println);
        //7. What’s the highest value of all the transactions?
        Integer maxValue = transactions.stream()
                .map(Transaction::getValue)
                .reduce(Integer::max)
                .get();
        //8. Find the transaction with the smallest value.
        Transaction transaction = transactions.stream()
                .reduce((a,b) -> a.getValue() < b.getValue() ? a : b)
                .get();
        
        System.out.println(list1);
        System.out.println(list2);
        System.out.println(list3);
        System.out.println(allTradersName);
        System.out.println(hasTraderInMilan);
        System.out.println(maxValue);
        System.out.println(transaction);
    }

    private static List<Transaction> buildDomains() {
        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)
                );
        return transactions;
    }
}

class Trader {

    private final String name;
    private final String city;

    public Trader(String n, String c) {
        this.name = n;
        this.city = c;
    }

    public String getName() {
        return this.name;
    }

    public String getCity() {
        return this.city;
    }

    public String toString() {
        return "Trader:" + this.name + " in " + this.city;
    }
}

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;
    }

    public Trader getTrader() {
        return this.trader;
    }

    public int getYear() {
        return this.year;
    }

    public int getValue() {
        return this.value;
    }

    public String toString() {
        return "{" + this.trader + ", " + "year: " + this.year + ", " + "value:" + this.value + "}";
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,943评论 2 8
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,446评论 25 708
  • 最近看了很多关于读书的文章,谈到了一年要看多少本书,一个月要看多少本书,回想一下前段时间坚持收听人民日报夜读,坚持...
    初因阅读 125评论 0 0
  • 自去年七夕那天,下班回家的公交车上被陌生人搭讪之后,每当有陌生人跟我说话,我都是尽量打手势。 可能是面相比...
    就让我为遇见你伏笔_阅读 161评论 0 0