流的使用

Stream API是java8的新特性;

功能或作用:简洁地表达复杂的数据处理查询;此外,流可以透明地并行化。

package lambdasinaction.chap5;

import lambdasinaction.chap5.*;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

public class PuttingIntoPractice{
    public static void main(String ...args){    
        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)
        );

		//查询2011年发生的交易
        /*
        * CREATED BY MILLER FAN
        * time:20190216
        * */
        List<Transaction> transactionsListHappenedIn2011 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                .collect(toList());




        
        
        // Query 1: Find all transactions from year 2011 and sort them by value (small to high).
        List<Transaction> tr2011 = transactions.stream()
                                               .filter(transaction -> transaction.getYear() == 2011)
                                               .sorted(comparing(Transaction::getValue))
                                               .collect(toList());
        System.out.println(tr2011);


        //交易员都在哪些不同的城市工作过
        /*
         * Created by miller fan    缺点:没有使用lambda可以复合使用的特性
         * time:20190216
         * */
        List<String> cityList = transactions.stream()
                .map(t -> t.getTrader())
                .distinct()
                .map(p -> p.getCity())
                .distinct()
                .collect(toList());
        
        // Query 2: What are all the unique cities where the traders work?
        List<String> cities = 
            transactions.stream()
                        .map(transaction -> transaction.getTrader().getCity())
                        .distinct()
                        .collect(toList());
        System.out.println(cities);

        //查询所欲来自于剑桥的交易员,并按姓名排序
        /*
         * CREATED BY MILLER FAN
         * time:20190216
         * my error : 视图在map中获得交易员的名字后排序,发现这样映射后就是List<String>,显然是不正确的
         * */
        List<Trader> traderListFromCambridge = transactions.stream()
                .map(t -> t.getTrader())
                .filter(trader -> trader.getCity().equals("Cambridge"))
                .distinct()
                .sorted(comparing(Trader::getName))
                .collect(toList());

        // Query 3: Find all traders from Cambridge and sort them by name.
        
        List<Trader> traders = 
            transactions.stream()
                        .map(Transaction::getTrader)
                        .filter(trader -> trader.getCity().equals("Cambridge"))
                        .distinct()
                        .sorted(comparing(Trader::getName))
                        .collect(toList());
        System.out.println(traders);


        //返回所有交易员的姓名的字符串,并按字母顺序排序
        /*
         * CREATED BY MILLER FAN
         * time:20190216
         * error : 获得姓名的字符串列表后,不能正确使用首字母排序 错误写法
         * .sorted(comparing(String -> String.toCharArray).findFirst)
         * */
        List<String> names = transactions.stream()
                .map(transaction -> transaction.getTrader().getName())
                .distinct()
                .sorted()
                .collect(toList());
        //返回一个字符串,还是字符串的列表?
        
        // Query 4: Return a string of all traders’ names sorted alphabetically.
        
        String traderStr = 
            transactions.stream()
                        .map(transaction -> transaction.getTrader().getName())
                        .distinct()
                        .sorted()
                        .reduce("", (n1, n2) -> n1 + n2);
        System.out.println(traderStr);



        //有没有交易员是来自米兰工作的?  考虑短路
        /*
         * CREATED BY MILLER FAN
         * time:20190216
         * error :这里为什么不许使用Optional
         * */

        boolean traderFromMilan = transactions.stream()
                .map(t -> t.getTrader())
                .anyMatch(p -> p.getCity().equals("Milan"));

        // Query 5: Are there any trader based in Milan?
        
        boolean milanBased =
            transactions.stream()
                        .anyMatch(transaction -> transaction.getTrader()
                                                            .getCity()
                                                            .equals("Milan")
                                 );
        System.out.println(milanBased);


        //打印生活在剑桥的交易员的所有交易额
        /*
         * CREATED BY MILLER FAN
         * time:20190216
         * error :没有过滤得到同意属性的交易列表,考虑问题的方向错误
         * */
        transactions.stream().filter(t -> t.getTrader().getCity().equals("Cambridge"))
                .map(t -> t.getValue())
                .forEach(System.out::println);
        
        // Query 6: Update all transactions so that the traders from Milan are set to Cambridge.
        transactions.stream()
                    .map(Transaction::getTrader)
                    .filter(trader -> trader.getCity().equals("Milan"))
                    .forEach(trader -> trader.setCity("Cambridge"));
        System.out.println(transactions);

        //所欲交易中交易额最高的是多少?
        /*
        * Created by miller fan
        * time : 20190216
        * */
        int v = transactions.stream()
                .map(t -> t.getValue())
                .reduce(0, Integer::max);
        
        
        // Query 7: What's the highest value in all the transactions?
        int highestValue = 
            transactions.stream()
                        .map(Transaction::getValue)
                        .reduce(0, Integer::max);
        System.out.println(highestValue);


        //找出交易额做小的交易 ---这不是交易额最小的交易,而是交易的最小值,而且这样明显不合理,初值该怎么设置?
        int vMin = transactions.stream()
                .map(t -> t.getValue())
                .reduce(999999999, Integer::min);

        //流支持最大值和最小值的方法,它们可以接受一个Comparator作为参数
        Optional<Transaction>  transaction = transactions.stream()
                .min(comparing(t -> t.getValue()));


        //另一种写法是
        Optional<Transaction> transaction1 = transactions.stream()
                .reduce((t1 ,t2) -> t1.getValue() < t2.getValue() ? t1 : t2);
    }
}

针对流,我的练习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值