美文网首页
Stream初体验

Stream初体验

作者: ilaoke | 来源:发表于2016-12-07 19:41 被阅读26次

最近在看《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 + "}";
    }
}

相关文章

  • Java8 Stream语法详解

    1. Stream初体验 我们先来看看Java里面是怎么定义Stream的: A sequence of elem...

  • Stream初体验

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

  • MongoDB Change Stream初体验

    Change Stream是MongoDB从3.6开始支持的新特性。这个新特性有哪些奇妙之处,会给我们带来什么便利...

  • JAVA8新特性: Stream-集合流操作

    Stream类全路径为:java.util.stream.Stream Stream简介 Stream原理 Str...

  • yii初体验(7-15)

    yii初体验(7)视图 yii初体验(8)模块 yii初体验(9) 小部件widgets yii初体验(10) 前...

  • Stream流

    一、创建流 Arrays.stream Stream.of Collection.stream Stream.it...

  • JDK8新特性之Stream流

    是什么是Stream流 java.util.stream.Stream Stream流和传统的IO流,它们都叫流,...

  • 2018-04-03

    Stream初探 一:stream.Readable & stream.Writable 1:模拟实现 strea...

  • 异步 Stream

    flutter 异步方式 Future Async/await Stream Stream stream 是一个事...

  • Java8新特性

    java.util.stream.Stream 注意事项 使用java.util.stream.Collector...

网友评论

      本文标题:Stream初体验

      本文链接:https://www.haomeiwen.com/subject/ubhjmttx.html