博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Stream API
阅读量:4230 次
发布时间:2019-05-26

本文共 4071 字,大约阅读时间需要 13 分钟。

以前对集合中元素进行操作的时候需要一个一个遍历的去做,找出符合条件的数据,这样做真的不要太繁琐= =。

sql中却有很强的筛选信息的能力,而且也可以返回你想要的结果。

借鉴于sql语句,Stream诞生了,Stream是集合包中新添加的一个类,

说它是集合呢,又不太像,因为Stream可以是无线的,可以看做是一个后面数据未知的集合吧。== 不好理解

打个比方,看电影,如果电影是被我们下载下来看的,就是集合,如果是在线看的,那么后面的数据其实你的电脑还是不知道的,就是Stream。

大概就是这么个意思吧。

Stream大概就这些个api

filter 过滤,类似于sql中的where, 条件的返回值应该是boolean类型的,真假是用来筛选的嘛。

distinct 去重复

skip 输入数字,跳过多少个

limit 限制输入,和数据库中一样

map 数据间的转换,T -> R,比如我们从一个对象集合中返回名字啊

sorted 排序,入参是个Comparator接口

anyMatch 是否存在一个以上满足条件的,返回boolean

allMatch 是否都满足条件

findAny 找到任何一个满足条件的,随便找,没有顺序,比找第一个会效率高

findFirst 找到第一个

forEach T ->void转换,一般用来打印或者存值啥的

collect 用什么方式收集数据,一般有list set map

reduce 用来求和取值的

count 计数

下面介绍一个例子,通过这个例子,大概都能了解吧

对交易员交易信息处理的例子:

实体类:

public 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 name;    }    public String getCity() {        return city;    }    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 int getYear() {        return year;    }    public int getValue() {        return value;    }    public Trader getTrader() {        return trader;    }    public String toString(){        return "("+this.trader+",year:"+this.year+","+"value:"+this.value+")";    }}
先加一些数据:

Trader raoul=new Trader("Taoul","Cambridge");Trader mario=new Trader("Mario","Milan");Trader alan=new Trader("Alan","Cambridge");Trader brian=new Trader("Brian","Cambridge");List
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
tr2011= transactions.stream()//转化为流 .filter(transaction -> transaction.getYear()==2011)//筛选出返回true的结果 .sorted(Comparator.comparing(Transaction::getValue))//排序 .collect(Collectors.toList());//用List收集System.out.println(tr2011);
2交易员都在哪些不同的城市工作过?

List
cities= transactions.stream() .map(transaction -> transaction.getTrader().getCity())//信息转化啦,把对象变成城市的字符串 .distinct()//去掉重复 .collect(Collectors.toList());System.out.println(cities);
Set可以自动去重复,大家都懂的- -

Set
cities2= transactions.stream() .map(transaction -> transaction.getTrader().getCity()) .collect(Collectors.toSet());System.out.println(cities2);
3查找所有来自剑桥的交易员,并按名字排序:

List
traders= transactions.stream() .map(Transaction::getTrader)//转换成交易员信息 .filter(trader -> trader.getCity().equals("Cambridge"))//筛选 .distinct() .sorted(Comparator.comparing(Trader::getName)) .collect(Collectors.toList());System.out.println(traders);
4返回所有交易员的名字字符串,并按字母顺序排序:

String traderStr=        transactions.stream()        .map(transaction -> transaction.getTrader().getName())        .distinct()        .sorted()        .reduce("",(n1,n2)->n1+n2);//""表示初值,n1表示上一次的返回结果,n2为这一次的值,n1+n2位这一次返回结果System.out.println(traderStr);
5有没有交易员是在米兰工作的?

boolean milanBased=        transactions.stream()        .anyMatch(transaction -> transaction.getTrader().getCity().equals("Milan"));//有一个就可以System.out.println(milanBased);
6打印生活在剑桥的交易员的所有交易额:

transactions.stream().filter(transaction -> "Cambridge".equals(transaction.getTrader().getCity()))        .map(Transaction::getValue)        .forEach(System.out::println);
7所有交易中,最高的交易额是多少?

Optional
highestValue= transactions.stream() .map(Transaction::getValue)//得到交易额 .reduce(Integer::max);//每次保留大的System.out.println(highestValue.get());
8找到交易额最小的交易:

Optional
smallestTransaction= transactions.stream() .reduce((t1,t2)->t1.getValue()

转载地址:http://mljqi.baihongyu.com/

你可能感兴趣的文章
Pro Jakarta Commons
查看>>
Pro JSP, Third Edition
查看>>
LightWave 3D 8 Revealed
查看>>
The Cg Tutorial: The Definitive Guide to Programmable Real-Time Graphics
查看>>
Operating Systems Design and Implementation (3rd Edition)
查看>>
Beginning Visual C# 2005
查看>>
Professional C# 2005
查看>>
Faster Smarter Beginning Programming
查看>>
The Essence of Object-Oriented Programming with Java and UML
查看>>
ROI of Software Process Improvement: Metrics for Project Managers and Software Engineers
查看>>
FileMaker 8 Functions and Scripts Desk Reference
查看>>
Web Security Field Guide
查看>>
Computer Animation: Algorithms and Techniques
查看>>
Multimedia-based Instructional Design
查看>>
3D Videocommunication : Algorithms, concepts and real-time systems in human centred communication
查看>>
Guide to Computer Animation
查看>>
Character Development and Storytelling for Games
查看>>
Six Sigma--The First 90 Days
查看>>
GSM, GPRS and Edge Performance: Evolution towards 3G/UMTS
查看>>
Advanced Linux 3D Graphics Programming
查看>>