Java Lambda表达式初探Word文件下载.docx

上传人:b****7 文档编号:22447025 上传时间:2023-02-04 格式:DOCX 页数:28 大小:26.66KB
下载 相关 举报
Java Lambda表达式初探Word文件下载.docx_第1页
第1页 / 共28页
Java Lambda表达式初探Word文件下载.docx_第2页
第2页 / 共28页
Java Lambda表达式初探Word文件下载.docx_第3页
第3页 / 共28页
Java Lambda表达式初探Word文件下载.docx_第4页
第4页 / 共28页
Java Lambda表达式初探Word文件下载.docx_第5页
第5页 / 共28页
点击查看更多>>
下载资源
资源描述

Java Lambda表达式初探Word文件下载.docx

《Java Lambda表达式初探Word文件下载.docx》由会员分享,可在线阅读,更多相关《Java Lambda表达式初探Word文件下载.docx(28页珍藏版)》请在冰豆网上搜索。

Java Lambda表达式初探Word文件下载.docx

()->

).start();

正如你所见,之前无用的模板代码不见了!

如上所示,Lambda表达式一个常见的用法是取代(某些)匿名内部类,但Lambda表达式的作用不限于此。

Lambda表达式的原理

刚接触Lambda表达式可能觉得它很神奇:

不需要声明类或者方法的名字,就可以直接定义函数。

这看似是编译器为匿名内部类简写提供的一个小把戏,但事实上并非如此,Lambda表达式实际上是通过invokedynamic指令来实现的。

先别管这么多,下面是Lambda表达式几种可能的书写形式,“看起来”并不是很难理解。

Runnablerun=()->

HelloWorld"

//1

ActionListenerlistener=event->

buttonclicked"

//2

RunnablemultiLine=()->

{//3

Hello"

World"

};

BinaryOperator<

Long>

add=(Longx,Longy)->

x+y;

//4

addImplicit=(x,y)->

//5

通过上例可以发现:

Lambda表达式是有类型的,赋值操作的左边就是类型。

Lambda表达式的类型实际上是对应接口的类型。

Lambda表达式可以包含多行代码,需要用大括号把代码块括起来,就像写函数体那样。

大多数时候,Lambda表达式的参数表可以省略类型,就像代码2和5那样。

这得益于javac的类型推导机制,编译器可以根据上下文推导出类型信息。

表面上看起来每个Lambda表达式都是原来匿名内部类的简写形式,该内部类实现了某个函数接口(FunctionalInterface),但事实比这稍微复杂一些,这里不再展开。

所谓函数接口是指内部只有一个接口函数的接口。

Java是强类型语言,无论有没有显式指明,每个变量和对象都必须有明确的类型,没有显式指定的时候编译器会尝试确定类型。

Lambda表达式的类型就是对应函数接口的类型。

Lambda表达式和Stream

Lambda表达式的另一个重要用法,是和Stream一起使用。

Streamisasequenceofelementssupportingsequentialandparallelaggregateoperations。

Stream就是一组元素的序列,支持对这些元素进行各种操作,而这些操作是通过Lambda表达式指定的。

可以把Stream看作JavaCollection的一种视图,就像迭代器是容器的一种视图那样(但Stream不会修改容器中的内容)。

下面例子展示了Stream的常见用法。

例子1

假设需要从一个字符串列表中选出以数字开头的字符串并输出,Java7之前需要这样写:

List<

String>

list=Arrays.asList("

1one"

"

two"

three"

4four"

for(Stringstr:

list){

if(Character.isDigit(str.charAt(0))){

System.out.println(str);

}

而Java8就可以这样写:

list.stream()//1.得到容器的Steam

.filter(str->

Character.isDigit(str.charAt(0)))//2.选出以数字开头的字符串

.forEach(str->

System.out.println(str));

//3.输出字符串

上述代码首先1.调用List.stream()方法得到容器的Stream,2.然后调用filter()方法过滤出以数字开头的字符串,3.最后调用forEach()方法输出结果。

使用Stream有两个明显的好处:

减少了模板代码,只用Lambda表达式指明所需操作,代码语义更加明确、便于阅读。

将外部迭代改成了Stream的内部迭代,方便了JVM本身对迭代过程做优化(比如可以并行迭代)。

例子2

假设需要从一个字符串列表中,选出所有不以数字开头的字符串,将其转换成大写形式,并把结果放到新的集合当中。

Java8书写的代码如下:

Set<

newList=

list.stream()//1.得到容器的Stream

!

Character.isDigit(str.charAt(0)))//2.选出不以数字开头的字符串

.map(String:

:

toUpperCase)//3.转换成大写形式

.collect(Collectors.toSet());

//4.生成结果集

上述代码首先1.调用List.stream()方法得到容器的Stream,2.然后调用filter()方法选出不以数字开头的字符串,3.之后调用map()方法将字符串转换成大写形式,4.最后调用collect()方法将结果转换成Set。

这个例子还向我们展示了方法引用(methodreferences,代码中标号3处)以及收集器(Collector,代码中标号4处)的用法,这里不再展开说明。

通过这个例子我们看到了Stream链式操作,即多个操作可以连成一串。

不用担心这会导致对容器的多次迭代,因为不是每个Stream的操作都会立即执行。

Stream的操作分成两类,一类是中间操作(intermediateoperations),另一类是结束操作(terminaloperation),只有结束操作才会导致真正的代码执行,中间操作只会做一些标记,表示需要对Stream进行某种操作。

这意味着可以在Stream上通过关联多种操作,但最终只需要一次迭代。

如果你熟悉SparkRDD,对此应该并不陌生。

参考文献:

compact1,compact2,compact3

java.util.stream

InterfaceStream<

T>

TypeParameters:

T-thetypeofthestreamelements

AllSuperinterfaces:

AutoCloseable,BaseStream<

T,Stream<

>

publicinterfaceStream<

extendsBaseStream<

Asequenceofelementssupportingsequentialandparallelaggregateoperations.ThefollowingexampleillustratesanaggregateoperationusingStreamandIntStream:

intsum=widgets.stream()

.filter(w->

w.getColor()==RED)

.mapToInt(w->

w.getWeight())

.sum();

Inthisexample,widgetsisaCollection<

Widget>

.WecreateastreamofWidgetobjectsviaCollection.stream(),filterittoproduceastreamcontainingonlytheredwidgets,andthentransformitintoastreamofintvaluesrepresentingtheweightofeachredwidget.Thenthisstreamissummedtoproduceatotalweight.

InadditiontoStream,whichisastreamofobjectreferences,thereareprimitivespecializationsforIntStream,LongStream,andDoubleStream,allofwhicharereferredtoas"

streams"

andconformtothecharacteristicsandrestrictionsdescribedhere.

Toperformacomputation,streamoperationsarecomposedintoastreampipeline.Astreampipelineconsistsofasource(whichmightbeanarray,acollection,ageneratorfunction,anI/Ochannel,etc),zeroormoreintermediateoperations(whichtransformastreamintoanotherstream,suchasfilter(Predicate)),andaterminaloperation(whichproducesaresultorside-effect,suchascount()orforEach(Consumer)).Streamsarelazy;

computationonthesourcedataisonlyperformedwhentheterminaloperationisinitiated,andsourceelementsareconsumedonlyasneeded.

Collectionsandstreams,whilebearingsomesuperficialsimilarities,havedifferentgoals.Collectionsareprimarilyconcernedwiththeefficientmanagementof,andaccessto,theirelements.Bycontrast,streamsdonotprovideameanstodirectlyaccessormanipulatetheirelements,andareinsteadconcernedwithdeclarativelydescribingtheirsourceandthecomputationaloperationswhichwillbeperformedinaggregateonthatsource.However,iftheprovidedstreamoperationsdonotofferthedesiredfunctionality,theBaseStream.iterator()andBaseStream.spliterator()operationscanbeusedtoperformacontrolledtraversal.

Astreampipeline,likethe"

widgets"

exampleabove,canbeviewedasaqueryonthestreamsource.Unlessthesourcewasexplicitlydesignedforconcurrentmodification(suchasaConcurrentHashMap),unpredictableorerroneousbehaviormayresultfrommodifyingthestreamsourcewhileitisbeingqueried.

Moststreamoperationsacceptparametersthatdescribeuser-specifiedbehavior,suchasthelambdaexpressionw->

w.getWeight()passedtomapToIntintheexampleabove.Topreservecorrectbehavior,thesebehavioralparameters:

mustbenon-interfering(theydonotmodifythestreamsource);

and

inmostcasesmustbestateless(theirresultshouldnotdependonanystatethatmightchangeduringexecutionofthestreampipeline).

SuchparametersarealwaysinstancesofafunctionalinterfacesuchasFunction,andareoftenlambdaexpressionsormethodreferences.Unlessotherwisespecifiedtheseparametersmustbenon-null.

Astreamshouldbeoperatedon(invokinganintermediateorterminalstreamoperation)onlyonce.Thisrulesout,forexample,"

forked"

streams,wherethesamesourcefeedstwoormorepipelines,ormultipletraversalsofthesamestream.AstreamimplementationmaythrowIllegalStateExceptionifitdetectsthatthestreamisbeingreused.However,sincesomestreamoperationsmayreturntheirreceiverratherthananewstreamobject,itmaynotbepossibletodetectreuseinallcases.

StreamshaveaBaseStream.close()methodandimplementAutoCloseable,butnearlyallstreaminstancesdonotactuallyneedtobeclosedafteruse.Generally,onlystreamswhosesourceisanIOchannel(suchasthosereturnedbyFiles.lines(Path,Charset))willrequireclosing.Moststreamsarebackedbycollections,arrays,orgeneratingfunctions,whichrequirenospecialresourcemanagement.(Ifastreamdoesrequireclosing,itcanbedeclaredasaresourceinatry-with-resourcesstatement.)

Streampipelinesmayexecuteeithersequentiallyorinparallel.Thisexecutionmodeisapropertyofthestream.Streamsarecreatedwithaninitialchoiceofsequentialorparallelexecution.(Forexample,Collection.stream()createsasequentialstream,andCollection.parallelStream()createsaparallelone.)ThischoiceofexecutionmodemaybemodifiedbytheBaseStream.sequential()orBaseStream.parallel()methods,andmaybequeriedwiththeBaseStream.isParallel()method.

Since:

1.8

SeeAlso:

IntStream,LongStream,DoubleStream,java.util.stream

NestedClassSummary

NestedClasses

ModifierandTypeInterfaceandDescription

staticinterfaceStream.Builder<

AmutablebuilderforaStream.

MethodSummary

AllMethodsStaticMethodsInstanceMethodsAbstractMethodsDefaultMethods

ModifierandTypeMethodandDescription

booleanallMatch(Predicate<

?

superT>

predicate)

Returnswhetherallelementsofthisstreammatchtheprovidedpredicate.

booleananyMatch(Predicate<

Returnswhetheranyelementsofthisstreammatchtheprovidedpredicate.

static<

Stream.Builder<

builder()

ReturnsabuilderforaStream.

<

R,A>

Rcollect(Collector<

superT,A,R>

collector)

PerformsamutablereductionoperationontheelementsofthisstreamusingaCollector.

R>

Rcollect(Supplier<

supplier,BiConsumer<

R,?

accumulator,BiConsumer<

R,R>

combiner)

Performsamutablereductionoperationontheelementsofthisstream.

Stream<

concat(Stream<

extendsT>

a,Stream<

b)

Createsalazilyconcatenatedstreamwhoseelementsarealltheelementsofthefirststreamfollowedbyalltheelementsofthesecondstream.

longcount()

Returnsthecountofelementsinthisstream.

Stream<

distinct()

Returnsastreamconsistingofthedistinctelements(accordingtoObject.equals(Object))ofthisstream.

empty()

ReturnsanemptysequentialStream.

filter(Predicate<

Returnsastreamconsistingoftheelementsofthisstreamthatmatchthegivenpredicate.

Optional<

findAny()

ReturnsanOptionaldescribingsomeelementofthestream,oranemptyOptionalifthestreamisempty.

findFirst()

ReturnsanOptionaldescribingthefirstelementofthisstream,oranemptyOptionalifthestreamisempty.

flatMap

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 农学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1