簡體   English   中英

Java Stream將整數列表分為3部分,每部分的總和

[英]Java Stream divide integer list to 3 parts and sum of each parts

我需要將整數列表分為相等的部分,並打印每個數組的總和

例如[4、2、3、4、1、1、1、2、1]

除以[4,2,3],[4,1.1],[1,2,1]並將每個最終結果加和964

需要做與Java 8流api

AtomicInteger counter = new AtomicInteger(0);

Integer[] array = {4, 2, 3, 4, 1, 1, 1, 2, 1};


Arrays.asList(array).stream().collect(Collectors.groupingBy(it -> counter .getAndIncrement() / 3)).forEach((k,v)->System.out.println(k + " " + v));

它打印

{0=[4, 2, 3], 1=[4, 1, 1], 2=[1, 2, 1]}

我需要打印每個部分的總和964

謝謝

不要使用外部計數器。 由於流不保證特定的處理順序,因此不保證計數器更新確實反映了實際的元素位置。

簡單的解決方案並不那么復雜:

int[] array = {4, 2, 3, 4, 1, 1, 1, 2, 1};
int chunks = 3, chunkSize = array.length/chunks;
IntStream.range(0, chunks).forEach(i -> System.out.println(i+" "
    +Arrays.stream(array, i*=chunkSize, i+chunkSize).sum()));

如果數組長度不能被三整除,它將忽略多余的元素。

如果數組確實是Integer[]而不是int[] ,則必須將元素拆箱:

Integer[] array = {4, 2, 3, 4, 1, 1, 1, 2, 1};
int chunks = 3, chunkSize = array.length/chunks;
IntStream.range(0, chunks).forEach(i -> System.out.println(i+" "
    +Arrays.stream(array, i*=chunkSize, i+chunkSize)
           .mapToInt(Integer::intValue)
           .sum()));

上面的解決方案是“將整數列表分為3部分”,與您的問題的標題相匹配。 如果要拆分為長度為三的部分,只需將解決方案更改為

int chunkSize = 3;
IntStream.range(0, array.length/chunkSize).forEach(i -> System.out.println(i+" "
    +Arrays.stream(array, i*=chunkSize, i+chunkSize)
           .mapToInt(Integer::intValue)
           .sum()));

如果要通過處理最后一個可能較短的塊來處理不能被chunkSize整除的數組長度,則可以使用

Integer[] array = {4, 2, 3, 4, 1, 1, 1, 2, 1, 100};
int chunkSize = 3;
IntStream.range(0, (array.length+chunkSize-1)/chunkSize)
    .forEach(i -> System.out.println(i+" "
        +Arrays.stream(array, i*=chunkSize, Math.min(i+chunkSize, array.length))
               .mapToInt(Integer::intValue)
               .sum()));

您可以在具有Map<Integer, List<Integer>>的點處停止問題: {0=[4, 2, 3], 1=[4, 1, 1], 2=[1, 2, 1]}

你需要

  • 遍歷差異Lists
  • 總結他們的要素
  • 打印它們(或收集它們以構建一個int
Arrays.asList(array).stream()
    .collect(Collectors.groupingBy(it -> counter .getAndIncrement() / 3))
    .values()
    .stream()
    .mapToInt(val-> val.stream().mapToInt(Integer::intValue).sum())
    .forEach(System.out::print);

Workable Demo : print

得到一個String

String res = Arrays.asList(array).stream()
        .collect(Collectors.groupingBy(it -> counter .getAndIncrement() / 3))
        .values().stream()
        .map(val-> val.stream().mapToInt(Integer::intValue).sum())
        .map(String::valueOf)
        .collect(Collectors.joining());
        System.out.println(res);

Workable Demo : collect as String


較短但不易讀的方法可以是:

  • 迭代ints ,在您的情況下以3分隔: ints ...
  • 將每個映射到從indexindex+3的數組值的總和
IntStream.iterate(0,i->i+size)
    .limit(array.length/size)
    .map(i -> Arrays.stream(array).skip(i).limit(size).mapToInt(Integer::intValue).sum())
    .forEach(System.out::print);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM