jdk1.8新特性应用之Collection
之前说了jdk1.8几个新特性,现在看下实战怎么玩,直接看代码:
public List<MSG_ConMediaInfo> getConMediaInfoList(String liveType)
{
if (Util.isEmpty(liveType))
{
return null;
}
List<MSG_ConMediaInfo> conMediaInfoList = getConMediaInfoList();
if (Util.isNotEmpty(conMediaInfoList))
{
if (LIVE_TYPE_BEING.equals(liveType))
{
return conMediaInfoList.parallelStream()
.filter(s -> s != null)
.filter(s -> isLiveBeing(s))
.collect(Collectors.toList());
}
else if (LIVE_TYPE_PREVIEW.equals(liveType))
{
return conMediaInfoList.parallelStream()
.filter(s -> s != null)
.filter(s -> isLivePreview(s))
.collect(Collectors.toList());
}
else
{
return conMediaInfoList.parallelStream()
.filter(s -> s != null)
.filter(s -> liveType.equals(s.getLiveStatus()))
.collect(Collectors.toList());
}
}
return null;
} private boolean isLiveBeing(MSG_ConMediaInfo conMediaInfo)
{
String liveStatus = conMediaInfo.getLiveStatus();
if (LIVE_TYPE_BEING.equals(liveStatus))
{
return Boolean.TRUE;
}
if (LIVE_TYPE_PREVIEW.equals(liveStatus))
{
if (!isLivePreview(conMediaInfo))
{
return Boolean.TRUE;
}
}
return Boolean.FALSE;
} private boolean isLivePreview(MSG_ConMediaInfo conMediaInfo)
{
if (LIVE_TYPE_PREVIEW.equals(conMediaInfo.getLiveStatus()))
{
String startTime =
DateTools.timeTransform(conMediaInfo.getLiveStartTime(),
DateTools.DATE_PATTERN_24HOUR_16);
int result =
DateTools.compare(new Date(), DateTools.timeStr2Date(startTime, DateTools.DATE_PATTERN_24HOUR_16),
CompareDateFormate.yyyyMMddhhmmss);
//当前时间已超过直播开始时间
if (result != -1)
{
return Boolean.FALSE;
}
return Boolean.TRUE;
}
return Boolean.FALSE;
}
这里3个方法,第一个方法使用了lambda表达式,这里是一个List实例conMediaInfoList,通过调用parallelStream方法得到一个Stream接口,再调用它的filter方法,该方法的参数是一个函数式接口Predicate。步步推进,终于绕到函数式接口这个jdk1.8的新特性了。我们知道,lambda表达式使用的前提就是函数式接口。
那么首先让我们来看下Predicate:
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
package java.util.function; import java.util.Objects; /**
* Represents a predicate (boolean-valued function) of one argument.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #test(Object)}.
*
* @param <T> the type of the input to the predicate
*
* @since 1.8
*/
@FunctionalInterface
public interface Predicate<T> { /**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t); /**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
} /**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
default Predicate<T> negate() {
return (t) -> !test(t);
} /**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
} /**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param <T> the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
我们看到该接口只有一个抽象方法(只能有一个,否则就不能叫函数式接口),3个默认方法和一个静态方法。该接口只有一个参数t,返回一个布尔值。我们先看看能怎么用这个接口:
// Predicate接口实例predicate指代一段判断字符串s是否长度大于0的代码
Predicate<String> predicate = (s) -> s.length() > 0; // predicate应用,判断字符串wlf是否长度>0
predicate.test("wlf"); // predicate应用,判断字符串wlf是否长度<=0
predicate.negate().test("wlf"); // 方法引用:Objects.isNull返回一个boolean,
Predicate<Object> isNull = Objects::isNull; // 方法引用:String.isEmpty方法一个boolean
Predicate<String> isEmpty = String::isEmpty;
Predicate接口做的事情就是判断参数s是否符合方法体里的判断逻辑,而方法体的逻辑是由你自己实现的。上面分别判断了一个字符串的长度大于0、不大于0,对象是否为空,字符串是否为空。
我们溯流而上,接下来再看下Stream的filter方法
public interface Stream<T> extends BaseStream<T, Stream<T>> { /**
* Returns a stream consisting of the elements of this stream that match
* the given predicate.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* predicate to apply to each element to determine if it
* should be included
* @return the new stream
*/
Stream<T> filter(Predicate<? super T> predicate);
}
这个方法就是执行Predicate的判断逻辑,通过再返回一个Stream。再回过来看最开始的代码:
conMediaInfoList.parallelStream()
.filter(s -> s != null)
.filter(s -> isLiveBeing(s))
.collect(Collectors.toList());
我们看到lambda表达式里先判断MSG_ConMediaInfo实例是否不为null,再判断实例是否符合isLiveBeing方法里的判断逻辑,两个都返回true的话,继续调用collect方法返回一个List。
接下来聊下Stream接口。它表示在一组元素上一次执行的操作序列,包括中间操作或者最终操作,中间操作继续返回Stream,直到操作序列结束,执行最终操作。像上面的业务代码,filter是中间操作,collect是最终操作。那么Stream怎么创建呢?只能通过容器类来创建,有两个方法都可以返回Stream:
public interface Collection<E> extends Iterable<E> { /**
* Returns a sequential {@code Stream} with this collection as its source.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a sequential {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a sequential {@code Stream} over the elements in this collection
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Returns a possibly parallel {@code Stream} with this collection as its
* source. It is allowable for this method to return a sequential stream.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a parallel {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a possibly parallel {@code Stream} over the elements in this
* collection
* @since 1.8
*/
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}
Collection还有它的孩子们List、Set都可以通过parallelStream来创造一个Stream对象,然后才后面的那些lambda表达式。
jdk1.8新特性应用之Collection的更多相关文章
- JavaSE----API之集合(Collection、List及其子类、Set及其子类、JDK1.5新特性)
5.集合类 集合类的由来: 对象用于封装特有数据,对象多了须要存储:假设对象的个数不确定.就使用集合容器进行存储. 集合容器由于内部的数据结构不同,有多种详细容器.不断的向上抽取,就形成了集合框架. ...
- JDK1.5新特性,基础类库篇,集合框架(Collections)
集合框架在JDK1.5中增强特性如下: 一. 新语言特性的增强 泛型(Generics)- 增加了集合框架在编译时段的元素类型检查,节省了遍历元素时类型转换代码量. For-Loop循环(Enhanc ...
- jdk1.8新特性应用之Iterable
我们继续看lambda表达式的应用: public void urlExcuAspect(RpcController controller, Message request, RpcCallback ...
- JDK1.8新特性——Collector接口和Collectors工具类
JDK1.8新特性——Collector接口和Collectors工具类 摘要:本文主要学习了在Java1.8中新增的Collector接口和Collectors工具类,以及使用它们在处理集合时的改进 ...
- JDK1.8新特性(一) ----Lambda表达式、Stream API、函数式接口、方法引用
jdk1.8新特性知识点: Lambda表达式 Stream API 函数式接口 方法引用和构造器调用 接口中的默认方法和静态方法 新时间日期API default Lambda表达式 L ...
- JDK1.7新特性
jdk1.7新特性 1 对集合类的语言支持: 2 自动资源管理: 3 改进的通用实例创建类型推断: 4 数字字面量下划线支持: 5 switch中使用string: 6 二进制字面量: 7 简化可变参 ...
- jdk1.6新特性
1.Web服务元数据 Java 里的Web服务元数据跟微软的方案基本没有语义上的区别,自从JDK5添加了元数据功能(Annotation)之后,SUN几乎重构了整个J2EE体 系, 由于变化很大,干脆 ...
- JDK1.8 新特性
jdk1.8新特性知识点: Lambda表达式 函数式接口 *方法引用和构造器调用 Stream API 接口中的默认方法和静态方法 新时间日期API https://blog.csdn.net/qq ...
- JDK1.6新特性,WebService强化
Web service是一个平台独立的,松耦合的,自包含的.基于可编程的web的应用程序,可使用开放的XML标准来描述.发布.发现.协调和配置这些应用程序,用于开发分布式的互操作的应用程序. Web ...
随机推荐
- CodeForces 297C Splitting the Uniqueness (脑补构造题)
题意 Split a unique array into two almost unique arrays. unique arrays指数组各个数均不相同,almost unique arrays指 ...
- linux---网络相关配置,ssh服务,bash命令及优先级,元字符
- 二:临时配置网络(ip,网关,dns)+永久配置 临时配置: [root@nfs-server ~]# ifconfig ens32: flags=4163<UP,BROADCAST,RUN ...
- RabbitMQ消息队列(九)RPC开始应用吧
一 简单应用 RPC——远程过程调用,通过网络调用运行在另一台计算机上的程序的函数\方法,是构建分布式程序的一种方式.RabbitMQ是一个消息队列系统,可以在程序之间收发消息.利用RabbitMQ可 ...
- 七种常见经典排序算法总结(C++)
最近想复习下C++,很久没怎么用了,毕业时的一些经典排序算法也忘差不多了,所以刚好一起再学习一遍. 除了冒泡.插入.选择这几个复杂度O(n^2)的基本排序算法,希尔.归并.快速.堆排序,多多少少还有些 ...
- textbox和input限制文字长度
textbox 看下面 要求(限制140,并且显示还剩余多少个文字) <asp:textbox id="txt_xm" runat="server" on ...
- MoreEffectiveC++Item35 条款27: 要求或禁止对象产生于heap中
一 要求对象产生在heap中 阻止对象产生产生在non-heap中最简单的方法是将其构造或析构函数声明在private下,用一个public的函数去调用起构造和析构函数 class UPNumber ...
- Recording︱有价值的各类AI、机器学习比赛心得、经验抄录
今年kaggle华人优胜团队很多,所以经验.心得不少,都是干货慢慢收集. 一.[干货]Kaggle 数据挖掘比赛经验分享 github:https://github.com/ChenglongChen ...
- 基于视觉的 SLAM/Visual Odometry (VO) 开源资料、博客和论文列表
基于视觉的 SLAM/Visual Odometry (VO) 开源资料.博客和论文列表 以下为机器翻译,具体参考原文: https://github.com/tzutalin/awesome-vis ...
- CS231n课程笔记翻译2:图像分类笔记
译者注:本文智能单元首发,译自斯坦福CS231n课程笔记image classification notes,由课程教师Andrej Karpathy授权进行翻译.本篇教程由杜客翻译完成.Shiqin ...
- angular2.0学习日记1
使用NG2之前需要安装node以及Npm环境,并到node下下载ng2所需要得文件,具体配置请到https://angular.cn/docs/ts/latest/quickstart.html按照提 ...