博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lambda(四)
阅读量:6496 次
发布时间:2019-06-24

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

hot3.png

方法引用

ClassName:methodName   凡是使用lambda表达式的地方就可以使用方法引用。

artist->artist.getName();Artist::getName

上下等价

(id,name) -> new Artist(id,name);Artist::new

元素顺序

如果进来的流是无序的,出去的流也是无序的。比如set

foreach方法不能保证元素是按照顺序处理的foreachOrdered方法可以。

收集器

转换成其他集合

.stream().collect(TreeSet::new);
new ArrayList
().stream().collect(toMap(p->p,p->p));

转换成值

取最大值

Function
getLength = s -> s.length(); Optional
count = stringList.collect(maxBy(Comparator.comparing(getLength)))

取平均值

collect(averagingInt(list->list.size()))

数据分块

收集器 partitioningBy , 它接受一个流,并将其分成两部分,它使用Predicate 对象判断一个元素应该属于哪个部分,并根据返回值,进行分类得到Map<Boolean,List<T>>

数据分组

groupingBy 收集器,接受一个分类函数,接受一个Function 对象。

Map
>albums.collect(groupingBy(Album::getPersion))

字符串

artists.stream()        .map(Artist::getName)        .collect(Collectors.joining(",","[","]"));

使用map操作提取出艺术家的姓名,然后使用Collectors.joining收集流中的值,该方法可以方便的从一个流得到一个字符串,参数分别为 分隔符,前缀,后缀  输出[a,b,c,d]

组合收集器

下游收集器,用以收集最终结果的一个子集,生成器是生成最终结果的一剂配方,下游收集器则是生成部分结果的配方,主收集器会用到下游收集器。

public Map
numberOfAlbums(Stream
albums){ return albums.collect(groupingBy(album ->album.getMainMusician ,counting()));}

mapping 收集器,允许在收集器的容器上执行类似map的操作。但是需要指明使用什么样的集合类存储结果,比如toList()

public Map
numberOfAlbums(Stream
albums){ return albums.collect(groupingBy(Album::getMainMusician ,mapping(Album::getName,toList())));}

 

定制收集器

首先实现collector接口,

T  待收集元素的类型

A 累加器的类型

R 最终结果的类型

一个收集器由四部分组成,

supplier 工厂方法,用来创建容器;

accumulator 作用和reduce操作的第二个参数一样,它结合之前操作的结果和当前值,生成并返回新的值。accumulator 用于将流中的值叠加入容器中,

combiner 像reduce操作的第三个方法,如果有两个容器,我们需要将其合并。

finisher 我们已经将流中的值叠加入一个可变容器中,但这还不是我们想要的最终结果。这里调用了finisher方法,以便进行转换。

特征。特征是一组描述收集器的对象,框架可以对其适当优化

 

public interface Collector
{ /** * A function that creates and returns a new mutable result container. * * @return a function which returns a new, mutable result container */ Supplier
supplier(); /** * A function that folds a value into a mutable result container. * * @return a function which folds a value into a mutable result container */ BiConsumer
accumulator(); /** * A function that accepts two partial results and merges them. The * combiner function may fold state from one argument into the other and * return that, or may return a new result container. * * @return a function which combines two partial results into a combined * result */ BinaryOperator
combiner(); /** * Perform the final transformation from the intermediate accumulation type * {@code A} to the final result type {@code R}. * *

If the characteristic {@code IDENTITY_TRANSFORM} is * set, this function may be presumed to be an identity transform with an * unchecked cast from {@code A} to {@code R}. * * @return a function which transforms the intermediate result to the final * result */ Function

finisher(); /** * Returns a {@code Set} of {@code Collector.Characteristics} indicating * the characteristics of this Collector. This set should be immutable. * * @return an immutable set of collector characteristics */ Set
characteristics(); /** * Returns a new {@code Collector} described by the given {@code supplier}, * {@code accumulator}, and {@code combiner} functions. The resulting * {@code Collector} has the {@code Collector.Characteristics.IDENTITY_FINISH} * characteristic. * * @param supplier The supplier function for the new collector * @param accumulator The accumulator function for the new collector * @param combiner The combiner function for the new collector * @param characteristics The collector characteristics for the new * collector * @param
The type of input elements for the new collector * @param
The type of intermediate accumulation result, and final result, * for the new collector * @throws NullPointerException if any argument is null * @return the new {@code Collector} */ public static
Collector
of(Supplier
supplier, BiConsumer
accumulator, BinaryOperator
combiner, Characteristics... characteristics) { Objects.requireNonNull(supplier); Objects.requireNonNull(accumulator); Objects.requireNonNull(combiner); Objects.requireNonNull(characteristics); Set
cs = (characteristics.length == 0) ? Collectors.CH_ID : Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH, characteristics)); return new Collectors.CollectorImpl<>(supplier, accumulator, combiner, cs); } /** * Returns a new {@code Collector} described by the given {@code supplier}, * {@code accumulator}, {@code combiner}, and {@code finisher} functions. * * @param supplier The supplier function for the new collector * @param accumulator The accumulator function for the new collector * @param combiner The combiner function for the new collector * @param finisher The finisher function for the new collector * @param characteristics The collector characteristics for the new * collector * @param
The type of input elements for the new collector * @param
The intermediate accumulation type of the new collector * @param
The final result type of the new collector * @throws NullPointerException if any argument is null * @return the new {@code Collector} */ public static
Collector
of(Supplier
supplier, BiConsumer
accumulator, BinaryOperator
combiner, Function
finisher, Characteristics... characteristics) { Objects.requireNonNull(supplier); Objects.requireNonNull(accumulator); Objects.requireNonNull(combiner); Objects.requireNonNull(finisher); Objects.requireNonNull(characteristics); Set
cs = Collectors.CH_NOID; if (characteristics.length > 0) { cs = EnumSet.noneOf(Characteristics.class); Collections.addAll(cs, characteristics); cs = Collections.unmodifiableSet(cs); } return new Collectors.CollectorImpl<>(supplier, accumulator, combiner, finisher, cs); } /** * Characteristics indicating properties of a {@code Collector}, which can * be used to optimize reduction implementations. */ enum Characteristics { /** * Indicates that this collector is
concurrent, meaning that * the result container can support the accumulator function being * called concurrently with the same result container from multiple * threads. * *

If a {@code CONCURRENT} collector is not also {@code UNORDERED}, * then it should only be evaluated concurrently if applied to an * unordered data source. */ CONCURRENT, /** * Indicates that the collection operation does not commit to preserving * the encounter order of input elements. (This might be true if the * result container has no intrinsic order, such as a {@link Set}.) */ UNORDERED, /** * Indicates that the finisher function is the identity function and * can be elided. If set, it must be the case that an unchecked cast * from A to R will succeed. */ IDENTITY_FINISH }}

computeIfAbsent

public Aritst getArtist(String name){    // 如果name 为空则调用 name->this.readArtistFormDB(DB);    return artistCache.computeIfAbsent(name,this::readArtistFromDB);}

遍历map

java 8 为map 接口 新增了一个forEach方法,方法接受一个BiConsumer 对象(该对象接受两个参数,返回为空)

for(Map.Entry
> entry: albumsByArtist.entrySet()){ map.put(entry.getKey(),entry.getValue().size());}albumsByArtist.forEach((artist,albums)->{ map.put(artist,albums.size())})

转载于:https://my.oschina.net/haloooooo/blog/1829199

你可能感兴趣的文章
存储过程由结构表生成表
查看>>
C# 批处理制作静默安装程序包
查看>>
柯南君:看大数据时代下的IT架构(5)消息队列之RabbitMQ--案例(Work Queues起航)...
查看>>
2015 Multi-University Training Contest 2 1002 Buildings
查看>>
java 产生的固体物的基础上 增删改的SQL声明
查看>>
在自己的网站添加关注新浪关注按钮
查看>>
【MySQL笔记】mysql来源安装/配置步骤和支持中国gbk/gb2312编码配置
查看>>
一句话的设计模式(转)
查看>>
(剑指Offer)面试题54:表示数值的字符串
查看>>
Centos下安装mysql 总结
查看>>
ORM武器:NHibernate(三)五个步骤+简单对象CRUD+HQL
查看>>
UIScrollView offset in UINavigationController
查看>>
怎么从sqlserver 数据库导出 insert 的数据语句
查看>>
BZOJ4245 : [ONTAK2015]OR-XOR
查看>>
Android Properties 存储
查看>>
setenv 和 set
查看>>
.sh
查看>>
碱基序列的儿子最长上涨
查看>>
Android UI SurfaceView的使用-绘制组合图型,并使其移动
查看>>
C# 属性、索引
查看>>