您的位置:首页 > 编程语言 > Java开发

Java Stream(摘自java8 API文档及stackflow)

2017-08-27 20:12 197 查看
Streamoperationsaredividedintointermediate(Stream-producing)operationsand
terminal(value-orside-effect-producing)operations.Intermediateoperationsarealwayslazy.
1、Streamscanbeobtainedinanumberofways.
·     Froma Collection via
thestream()andparallelStream()methods;
·     Fromanarrayvia Arrays.stream(Object[]);
·     Fromstaticfactorymethodsonthestreamclasses,suchas Stream.of(Object[]), IntStream.range(int,
int) orStream.iterate(Object,UnaryOperator);
·     Thelinesofafilecanbeobtainedfrom BufferedReader.lines();
·     Streamsoffilepathscanbeobtainedfrommethodsin Files;
·     Streamsofrandomnumberscanbeobtainedfrom Random.ints();
·     Numerousotherstream-bearingmethodsintheJDK,including BitSet.stream(),Pattern.splitAsStream(java.lang.CharSequence),
and JarFile.stream().

2、Streamoperationsandpipelines

(1)Streamoperations

1、intermediateoperations

Intermediateoperationsreturnanewstream.Theyarealwayslazy.

Intermediateoperationsarefurth
ca43
erdividedinto
stateless(suchas
filter
and
map---
retainnostatefrompreviouslyseenelementwhenprocessinganewelement)andstatefuloperations(suchas
distinct
and
sorted---
).

Traversalofthepipelinesourcedoesnotbeginuntiltheterminaloperationofthepipelineisexecuted.

2、terminaloperations

Aftertheterminaloperationisperformed,thestreampipelineisconsideredconsumed,andcannolongerbeused.

Inalmostallcases,terminaloperationsareeager,completingtheirtraversalofthedatasourceandprocessingofthepipelinebeforereturning.Onlytheterminaloperationsiterator()andspliterator()arenot.(eg:
Stream.forEachor
IntStream.sum
)

 

Aboutshortcuiting:

 Anintermediateoperationisshort-circuitingif,whenpresentedwithinfiniteinput,itmayproduceafinitestreamasaresult.Aterminaloperationisshort-circuitingif,whenpresentedwithinfiniteinput,itmayterminate
infinitetime.Havingashort-circuitingoperationinthepipelineisanecessary,butnotsufficient,conditionfortheprocessingofaninfinitestreamtoterminatenormallyinfinitetime.

3、SideEffect解析(摘自stackflow)

链接:https://stackoverflow.com/questions/1073909/side-effect-whats-this?noredirect=1

Asideeffectisanythingamethoddoesbesidescomputingandreturningavalue.Anychangeofinstanceorclassfieldvaluesisasideeffect,asisdrawingsomethingonthescreen,writingtoafileoranetworkconnection.

Strictlyspeaking,a"function"isdefinedasnothavingsideeffects-whichiswhyJavausestheword"method"instead.Arealfunctionwithnoreturnvaluewouldbepointless.

Obviously,amethodthatdoesnothaveareturnvaluemusthavesomesortofsideeffectthatjustifiesitsexistence.Setmethodsareanexample-thesideeffectischangingtheobject'sinternalstate

ForExample:

Asideeffectiswhenamethodcallchangesaclass'sstate.So

 

publicclassSideEffectClass{

   privateintstate=0;

  publicdoSomething(intarg0){

       state+=arg0;

   }

}

Here,doSomething(intarg0)hasthesideeffectofchangingthestatevariable.

Whenyouthinkofaprogram,youcanthinkofitasinstructions+state+input.(指令+状态+输入)Soifthedomainofaprogramistherangeofallpossibleinput*state,andtheprogramhassideeffects,youcanseethatthecodomain(值域)
ofpossibleresultsfortheapplicationcangrowexplosively,asthenumberofsideeffectsincrease.Thismakesthepossiblestatesfortheprogramlarge,whichleadstocomplicatedtesting.Thefunctionalprogrammingparadigmisdesignedtoeliminatesideeffects.
Bymakingfunctionsfirstclasscitizensandbymakingalldeclarationsimmutablefunctionalprogrammingpreventssideeffects,whichmakesfunctionalprogrammingshineinparallelprocessing,assynchronizationissuesarereduced.

Examplefromapi:

Asanexampleofhowtotransformastreampipelinethatinappropriatelyusesside-effectstoonethatdoesnot,thefollowingcodesearchesastreamofstringsforthosematchingagivenregularexpression,andputs
thematchesinalist.
    ArrayList<String>results=newArrayList<>();
    stream.filter(s->pattern.matcher(s).matches())
    .forEach(s->results.add(s)); //Unnecessaryuseofside-effects!
Thiscodeunnecessarilyusesside-effects.Ifexecutedinparallel,thenon-thread-safetyofArrayListwouldcauseincorrectresults,andaddingneededsynchronizationwouldcausecontention,underminingthebenefit
ofparallelism.Furthermore,usingside-effectshereiscompletelyunnecessary;theforEach()cansimplybereplacedwithareductionoperationthatissafer,moreefficient,andmoreamenabletoparallelization:
 
    List<String>results=
        stream.filter(s->pattern.matcher(s).matches())
        .collect(Collectors.toList()); //Noside-effects!

4、Ordering

Certainstreamsources(suchasListorarrays)areintrinsicallyordered,whereasothers(suchasHashSet)arenot.Someintermediateoperations,suchassorted(),mayimposeanencounterorderonanotherwiseunordered
stream,andothersmayrenderanorderedstreamunordered,suchasBaseStream.unordered().Further,someterminaloperationsmayignoreencounterorder,suchasforEach().
Ifastreamisordered,mostoperationsareconstrainedtooperateontheelementsintheirencounterorder;ifthesourceofastreamisaListcontaining[1,2,3],thentheresultofexecutingmap(x->x*2)must
be[2,4,6].However,ifthesourcehasnodefinedencounterorder,thenanypermutation(序列)ofthevalues[2,4,6]wouldbeavalidresult.

5、Reductionoperations

Areductionoperation(alsocalledafold)takesasequenceofinputelementsandcombinesthemintoasinglesummaryresultbyrepeatedapplicationofacombiningoperation,suchasfindingthesum
ormaximumofasetofnumbers,oraccumulatingelementsintoalist.Thestreamsclasseshavemultipleformsofgeneralreductionoperations,calledreduce()andcollect(),
aswellasmultiplespecializedreductionformssuchassum(),max(),orcount().
(1)未使用reduce:

intsum=0;

   for(intx:numbers){

      sum+=x;

   }

(2)使用reduce

 
   intsum=numbers.stream().reduce(0,(x,y)->x+y);

  or:

    intsum=numbers.stream().reduce(0,Integer::sum);

(3)areduceoperationonelementsoftype<T>yieldingaresultoftype<U>requiresthreeparameters:

 <U>Ureduce(Uidentity,BiFunction<U,?superT,U>accumulator,

          BinaryOperator<U>combiner);

[/code]
identityelement:bothaninitialseedvalueforthereductionandadefaultresultiftherearenoinputelements.

accumulatorfunction:takesapartialresultandthenextelement,andproducesanewpartialresult.

combinerfunction:combinestwopartialresultstoproduceanewpartialresult.

6、Mutablereduction

Amutablereductionoperationaccumulatesinputelementsintoamutableresultcontainer,suchasaCollectionorStringBuilder,asitprocessestheelementsinthestream.

ordinaryreduction:

   Stringconcatenated=strings.reduce("",String::concat)
[/code]
[/code]
mutablereductionoperation:collect(),itcollectstogetherthedesiredresultsintoaresultcontainersuchasaCollection.

 
[/code]
Acollectoperationrequiresthreefunctions:

asupplierfunction:toconstructnewinstancesoftheresultcontainer,anaccumulatorfunction:toincorporateaninputelementintoaresultcontainer,

acombiningfunction:tomergethecontentsofoneresultcontainerintoanother.Theformofthisisverysimilartothegeneralformofordinaryreduction:

<R>Rcollect(Supplier<R>supplier,

              BiConsumer<R,?superT>accumulator,

              BiConsumer<R,R>combiner);

Old:

ArrayList<String>strings=newArrayList<>();
[/code]
    for(Telement:stream){
[/code]
        strings.add(element.toString());
[/code]
    }
[/code]
New:

 
 ArrayList<String>strings=stream.collect(()->newArrayList<>(),
                                    (c,e)->c.add(e.toString()),
                                     (c1,c2)->c1.addAll(c2));
 
or,pullingthemappingoperationoutoftheaccumulatorfunction,wecouldexpressitmoresuccinctlyas:
 
    List<String>strings=stream.map(Object::toString)
                                 .collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
Here,oursupplierisjustthe
ArrayListconstructor
,theaccumulatoraddsthestringifiedelementtoan
ArrayList
,andthecombinersimplyuses
addAll

tocopythestringsfromonecontainerintotheother.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: