欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java8中Stream的使用以及分割list案例

 更新時間:2020年08月19日 08:42:41   作者:lee06152433  
這篇文章主要介紹了java8中Stream的使用以及分割list案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

一、Steam的優(yōu)勢

java8中Stream配合Lambda表達式極大提高了編程效率,代碼簡潔易懂(可能剛接觸的人會覺得晦澀難懂),不需要寫傳統(tǒng)的多線程代碼就能寫出高性能的并發(fā)程序

二、項目中遇到的問題

由于微信接口限制,每次導(dǎo)入code只能100個,所以需要分割list。但是由于code數(shù)量可能很大,這樣執(zhí)行效率就會很低。

1.首先想到是用多線程寫傳統(tǒng)并行程序,但是博主不是很熟練,寫出代碼可能會出現(xiàn)不可預(yù)料的結(jié)果,容易出錯也難以維護。

2.然后就想到Steam中的parallel,能提高性能又能利用java8的特性,何樂而不為。

三、廢話不多說,直接先貼代碼,然后再解釋(java8分割list代碼在標題四)。

1.該方法是根據(jù)傳入數(shù)量生成codes,private String getGeneratorCode(int tenantId)是我根據(jù)編碼規(guī)則生成唯一code這個不需要管,我們要看的是Stream.iterate

2.iterate()第一個參數(shù)為起始值,第二個函數(shù)表達式(看自己想要生成什么樣的流關(guān)鍵在這里),http://write.blog.csdn.net/postedit然后必須要通過limit方法來限制自己生成的Stream大小。parallel()是開啟并行處理。map()就是一對一的把Stream中的元素映射成ouput Steam中的 元素。最后用collect收集,

2.1 構(gòu)造流的方法還有Stream.of(),結(jié)合或者數(shù)組可直接list.stream();

String[] array = new String[]{"1","2","3"} ;

stream = Stream.of(array)或者Arrays.Stream(array);

2.2 數(shù)值流IntStream

int[] array = new int[]{1,2,3};

IntStream.of(array)或者IntStream.ranage(0,3)

3.以上構(gòu)造流的方法都是已經(jīng)知道大小,對于通過入?yún)⒋_定的應(yīng)該圖中方法自己生成流。

四、java8分割list,利用StreamApi實現(xiàn)。

沒用java8前代碼,做個鮮明對比():

1.list是我的編碼集合(codes)。MAX_SEND為100(即每次100的大小去分割list),limit為按編碼集合大小算出的本次需要分割多少次。

2.我們可以看到其實就是多了個skip跟limit方法。skip就是舍棄stream前多少個元素,那么limit就是返回流前面多少個元素(如果流里元素少于該值,則返回全部)。然后開啟并行處理。通過循環(huán)我們的分割list的目標就達到了,每次取到的sendList就是100,100這樣子的。

3.因為我這里業(yè)務(wù)就只需要到這里,如果我們分割之后需要收集之后再做處理,那只需要改寫一下就ok;如:

List<List<String>> splitList = Stream.iterate(0,n->n+1).limit(limit).parallel().map(a->{

 List<String> sendList = list.stream().skip(a*MAX_SEND).limit(MAX_SEND).parallel().collect(Collectors.toList());

}).collect(Collectors.toList());

五、java8流里好像拿不到下標,所以我才用到構(gòu)造一個遞增數(shù)列當下標用,這就是我用java8分割list的過程,比以前的for循環(huán)看的爽心悅目,優(yōu)雅些,性能功也提高了。

如果各位有更好的實現(xiàn)方式,歡迎留言指教。

補充知識:聊聊flink DataStream的split操作

本文主要研究一下flink DataStream的split操作

實例

SplitStream<Integer> split = someDataStream.split(new OutputSelector<Integer>() {
  @Override
  public Iterable<String> select(Integer value) {
    List<String> output = new ArrayList<String>();
    if (value % 2 == 0) {
      output.add("even");
    }
    else {
      output.add("odd");
    }
    return output;
  }
});

本實例將dataStream split為兩個dataStream,一個outputName為even,另一個outputName為odd

DataStream.split

flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/datastream/DataStream.java

@Public
public class DataStream<T> {
 
 //......
 
 public SplitStream<T> split(OutputSelector<T> outputSelector) {
 return new SplitStream<>(this, clean(outputSelector));
 }
 
 //......
}

DataStream的split操作接收OutputSelector參數(shù),然后創(chuàng)建并返回SplitStream

OutputSelector

flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/collector/selector/OutputSelector.java

@PublicEvolving
public interface OutputSelector<OUT> extends Serializable {
 
 Iterable<String> select(OUT value);
 
}

OutputSelector定義了select方法用于給element打上outputNames

SplitStream

flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/datastream/SplitStream.java

@PublicEvolving
public class SplitStream<OUT> extends DataStream<OUT> {
 
 protected SplitStream(DataStream<OUT> dataStream, OutputSelector<OUT> outputSelector) {
 super(dataStream.getExecutionEnvironment(), new SplitTransformation<OUT>(dataStream.getTransformation(), outputSelector));
 }
 
 public DataStream<OUT> select(String... outputNames) {
 return selectOutput(outputNames);
 }
 
 private DataStream<OUT> selectOutput(String[] outputNames) {
 for (String outName : outputNames) {
  if (outName == null) {
  throw new RuntimeException("Selected names must not be null");
  }
 }
 
 SelectTransformation<OUT> selectTransform = new SelectTransformation<OUT>(this.getTransformation(), Lists.newArrayList(outputNames));
 return new DataStream<OUT>(this.getExecutionEnvironment(), selectTransform);
 }
 
}

SplitStream繼承了DataStream,它定義了select方法,可以用來根據(jù)outputNames選擇split出來的dataStream;select方法創(chuàng)建了SelectTransformation

StreamGraphGenerator

flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java

@Internal
public class StreamGraphGenerator {
 
 //......
 
 private Collection<Integer> transform(StreamTransformation<?> transform) {
 
 if (alreadyTransformed.containsKey(transform)) {
  return alreadyTransformed.get(transform);
 }
 
 LOG.debug("Transforming " + transform);
 
 if (transform.getMaxParallelism() <= 0) {
 
  // if the max parallelism hasn't been set, then first use the job wide max parallelism
  // from theExecutionConfig.
  int globalMaxParallelismFromConfig = env.getConfig().getMaxParallelism();
  if (globalMaxParallelismFromConfig > 0) {
  transform.setMaxParallelism(globalMaxParallelismFromConfig);
  }
 }
 
 // call at least once to trigger exceptions about MissingTypeInfo
 transform.getOutputType();
 
 Collection<Integer> transformedIds;
 if (transform instanceof OneInputTransformation<?, ?>) {
  transformedIds = transformOneInputTransform((OneInputTransformation<?, ?>) transform);
 } else if (transform instanceof TwoInputTransformation<?, ?, ?>) {
  transformedIds = transformTwoInputTransform((TwoInputTransformation<?, ?, ?>) transform);
 } else if (transform instanceof SourceTransformation<?>) {
  transformedIds = transformSource((SourceTransformation<?>) transform);
 } else if (transform instanceof SinkTransformation<?>) {
  transformedIds = transformSink((SinkTransformation<?>) transform);
 } else if (transform instanceof UnionTransformation<?>) {
  transformedIds = transformUnion((UnionTransformation<?>) transform);
 } else if (transform instanceof SplitTransformation<?>) {
  transformedIds = transformSplit((SplitTransformation<?>) transform);
 } else if (transform instanceof SelectTransformation<?>) {
  transformedIds = transformSelect((SelectTransformation<?>) transform);
 } else if (transform instanceof FeedbackTransformation<?>) {
  transformedIds = transformFeedback((FeedbackTransformation<?>) transform);
 } else if (transform instanceof CoFeedbackTransformation<?>) {
  transformedIds = transformCoFeedback((CoFeedbackTransformation<?>) transform);
 } else if (transform instanceof PartitionTransformation<?>) {
  transformedIds = transformPartition((PartitionTransformation<?>) transform);
 } else if (transform instanceof SideOutputTransformation<?>) {
  transformedIds = transformSideOutput((SideOutputTransformation<?>) transform);
 } else {
  throw new IllegalStateException("Unknown transformation: " + transform);
 }
 
 // need this check because the iterate transformation adds itself before
 // transforming the feedback edges
 if (!alreadyTransformed.containsKey(transform)) {
  alreadyTransformed.put(transform, transformedIds);
 }
 
 if (transform.getBufferTimeout() >= 0) {
  streamGraph.setBufferTimeout(transform.getId(), transform.getBufferTimeout());
 }
 if (transform.getUid() != null) {
  streamGraph.setTransformationUID(transform.getId(), transform.getUid());
 }
 if (transform.getUserProvidedNodeHash() != null) {
  streamGraph.setTransformationUserHash(transform.getId(), transform.getUserProvidedNodeHash());
 }
 
 if (transform.getMinResources() != null && transform.getPreferredResources() != null) {
  streamGraph.setResources(transform.getId(), transform.getMinResources(), transform.getPreferredResources());
 }
 
 return transformedIds;
 }
 
 private <T> Collection<Integer> transformSelect(SelectTransformation<T> select) {
 StreamTransformation<T> input = select.getInput();
 Collection<Integer> resultIds = transform(input);
 
 // the recursive transform might have already transformed this
 if (alreadyTransformed.containsKey(select)) {
  return alreadyTransformed.get(select);
 }
 
 List<Integer> virtualResultIds = new ArrayList<>();
 
 for (int inputId : resultIds) {
  int virtualId = StreamTransformation.getNewNodeId();
  streamGraph.addVirtualSelectNode(inputId, virtualId, select.getSelectedNames());
  virtualResultIds.add(virtualId);
 }
 return virtualResultIds;
 }
 
 private <T> Collection<Integer> transformSplit(SplitTransformation<T> split) {
 
 StreamTransformation<T> input = split.getInput();
 Collection<Integer> resultIds = transform(input);
 
 // the recursive transform call might have transformed this already
 if (alreadyTransformed.containsKey(split)) {
  return alreadyTransformed.get(split);
 }
 
 for (int inputId : resultIds) {
  streamGraph.addOutputSelector(inputId, split.getOutputSelector());
 }
 
 return resultIds;
 }
 
 //......
}

StreamGraphGenerator里頭的transform會對SelectTransformation以及SplitTransformation進行相應(yīng)的處理

transformSelect方法會根據(jù)select.getSelectedNames()來addVirtualSelectNode

transformSplit方法則根據(jù)split.getOutputSelector()來addOutputSelector

小結(jié)

DataStream的split操作接收OutputSelector參數(shù),然后創(chuàng)建并返回SplitStream

OutputSelector定義了select方法用于給element打上outputNames

SplitStream繼承了DataStream,它定義了select方法,可以用來根據(jù)outputNames選擇split出來的dataStream

doc

DataStream Transformations

以上這篇java8中Stream的使用以及分割list案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • feignclient?https?接口調(diào)用報證書錯誤的解決方案

    feignclient?https?接口調(diào)用報證書錯誤的解決方案

    這篇文章主要介紹了feignclient?https?接口調(diào)用報證書錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Spring?ComponentScan的掃描過程解析

    Spring?ComponentScan的掃描過程解析

    這篇文章主要介紹了spring?ComponentScan的掃描過程解析,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • Java List接口的集合使用詳解

    Java List接口的集合使用詳解

    這篇文章主要介紹了Java集合操作之List接口及其實現(xiàn)方法,詳細分析了Java集合操作中List接口原理、功能、用法及操作注意事項,需要的朋友可以參考下
    2021-08-08
  • SpringBoot使用Flyway進行數(shù)據(jù)庫管理的操作方法

    SpringBoot使用Flyway進行數(shù)據(jù)庫管理的操作方法

    Flyway是一個開源的數(shù)據(jù)庫版本管理工具,并且極力主張“約定大于配置”,簡單、專注、強大。接下來通過本文給大家介紹SpringBoot使用Flyway進行數(shù)據(jù)庫管理的方法,感興趣的朋友一起看看吧
    2021-09-09
  • 如何基于SpringBoot實現(xiàn)人臉識別功能

    如何基于SpringBoot實現(xiàn)人臉識別功能

    人工智能時代的到來,相信大家已耳濡目染,虹軟免費,離線開放的人臉識別SDK,正推動著全行業(yè)進入刷臉時代,下面這篇文章主要給大家介紹了關(guān)于如何基于SpringBoot實現(xiàn)人臉識別功能的相關(guān)資料,需要的朋友可以參考下
    2022-05-05
  • java基于UDP實現(xiàn)在線聊天功能

    java基于UDP實現(xiàn)在線聊天功能

    這篇文章主要為大家詳細介紹了java基于UDP實現(xiàn)在線聊天功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-09-09
  • Spring Security 強制退出指定用戶的方法

    Spring Security 強制退出指定用戶的方法

    本篇文章主要介紹了Spring Security 強制退出指定用戶的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • spring-boot 如何實現(xiàn)單次執(zhí)行程序

    spring-boot 如何實現(xiàn)單次執(zhí)行程序

    這篇文章主要介紹了spring-boot 實現(xiàn)單次執(zhí)行程序方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 詳解Spring注解 @Configuration

    詳解Spring注解 @Configuration

    @Configuration 是 Spring 中的一個注解,它用于標記一個類為配置類,通過配置類可以定義和組裝 Spring Bean,并且支持高度靈活的配置方式。本問詳細介紹了Spring注解 @Configuration,感興趣的小伙伴可以參考一下
    2023-04-04
  • SpringBoot2.6.3集成quartz的方式

    SpringBoot2.6.3集成quartz的方式

    quartz是java里頭定時任務(wù)的經(jīng)典開源實現(xiàn),這里講述一下如何在SpringBoot2.6.3集成quartz,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2022-02-02

最新評論