java8 InAction Stream相关算子的基础使用

Stream算子

流Stream中的中间以及终端操作
在这里插入图片描述
例子:

public class Trader {

    private final String name;
    private final String city;


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

    public String getCity() {
        return city;
    }

    public String getName() {
        return name;
    }

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

}
public 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 +"}";  }
}

题目:
(1) 找出2011年发生的所有交易,并按交易额排序(从低到高)。
(2) 交易员都在哪些不同的城市工作过?
(3) 查找所有来自于剑桥的交易员,并按姓名排序。
(4) 返回所有交易员的姓名字符串,按字母顺序排序。
(5) 有没有交易员是在米兰工作的?
(6) 打印生活在剑桥的交易员的所有交易额。
(7) 所有交易中,最高的交易额是多少?
(8) 找到交易额最小的交易。

package java8inaction.chapter5;

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

public class Main {

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

        // (1) 找出2011年发生的所有交易,并按交易额排序(从低到高)。
        List<Transaction> transActions2011 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                .sorted(Comparator.comparing(Transaction::getValue))
                .collect(Collectors.toList());

        List<Transaction> transActions2011V2 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                .sorted((Transaction t1, Transaction t2) -> t1.getValue() - t2.getValue())
                .collect(Collectors.toList());
        System.out.println(transActions2011);
        System.out.println(transActions2011V2);

        // (2) 交易员都在哪些不同的城市工作过?
        List<String> diffCitys = transactions.stream().map(v -> v.getTrader().getCity()).distinct().collect(Collectors.toList());
        System.out.println(diffCitys);

        // (3) 查找所有来自于剑桥的交易员,并按姓名排序。
        List<Trader> q3 = transactions.stream()
                .map(Transaction::getTrader)
                .filter(v -> "Cambridge".equals(v.getCity()))
                .distinct()
                .sorted(Comparator.comparing(Trader::getName))
                .collect(Collectors.toList());
        System.out.println(q3);

        // (4) 返回所有交易员的姓名字符串,按字母顺序排序。
        String q4 = transactions.stream()
                .map(v -> v.getTrader().getName())
                .distinct()
                .sorted(String::compareTo)
                .collect(Collectors.joining("-"));
        System.out.println(q4);

        // (5) 有没有交易员是在米兰工作的?
        boolean b = transactions.stream().anyMatch(v -> "Milan".equals(v.getTrader().getCity()));
        System.out.println("有没有交易员是在米兰工作的 " + b);

        // (6) 打印生活在剑桥的交易员的所有交易额。
        transactions.stream()

                .filter(v -> "Cambridge".equals(v.getTrader().getCity()))
                .forEach(v -> {
                    System.out.println(v.getValue());
                });
        // (7) 所有交易中,最高的交易额是多少?
        Integer q7 = transactions.stream().map(Transaction::getValue)
                .reduce(Integer::max)
                .get();
        System.out.println(q7);

        // (8) 找到交易额最小的交易。
        transactions.stream().min(Comparator.comparing(Transaction::getValue))
                .ifPresent(System.out::println);

    }
}

Stream构建

Java8 创建Stream的几种方法:

  • 使用Stream.of生成流
  • 数组转换成流
  • 列表List转成流
  • generate生成流
  • iterate生成流
    如以下例子:
package java8inaction.chapter5;

import com.google.common.collect.Lists;

import java.util.Arrays;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class StreamBuilder {

    public static void main(String[] args) {
        // Stream.of 函数生成流
        String collect = Stream.of(1, 2, 3, 4, 5)
                .map(String::valueOf)
                .collect(Collectors.joining("-"));
        System.out.println(collect);

        // 2 数组生成流
        Arrays.stream(new String[]{"a","b"})
                .forEach(System.out::print);
        System.out.println();

        // 3 列表生成流
        Lists.newArrayList(100,200,300)
                .stream()
                .forEach(System.out::print);
        System.out.println();

        // generator 生成流

        Stream.generate(new Supplier<Object>(){


            int i = 0;
            int j = 1;
            @Override
            public Object get() {
                int tmp = j;
                j = i + j;
                i = tmp;
                return j;
            }
        }).limit(10).forEach(System.out::print);
        System.out.println();

        // iterate 生成无线流
        Stream.iterate(0, n -> n+1).limit(10).forEach(System.out::println);
        System.out.println("--------");
        IntStream.iterate(0, val -> val < 10, n -> n + 1)
                .limit(100)
                .forEach(System.out::println);
        System.out.println("--------");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值