繁体   English   中英

如何在Java8中将一个流简化为另一个流?

[英]How to reduce a stream into another stream in Java8?

例如,我想创建一个无限的数十个组的流,如下所示:

0=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
2=[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
...

我想使用inifinte int流作为输入,然后应将其分组。 如果第一个流迭代10次,则结果流应该仅迭代一次。

我的工作但不是很优雅的代码如下所示:

// create a stream from 0 (inclusive) to 100 (exclusive)
IntStream.iterate(0, i -> i+1).boxed().limit(100)

// slow down
.peek((i) -> {try {Thread.sleep(50);} catch (InterruptedException e) {}})

// group by tens
/* ugly: */.collect(Collectors.groupingBy(i -> i / 10)).entrySet()
/* not working: */ //.makeSequentialGroups(i -> i / 10)

// print to console
.forEach(System.out::println);  

如何在不进行收集和重新流式处理的情况下将一组int流式处理? (即使有可能,甚至不必使用拳击)

我怀疑是否有一种方法,因为在Java 8中不能不收集就不能从序列映射到Map,也不能不收集就不能对groupBy进行映射。 您可以创建自己的流,但是我怀疑您是否真的想走那条路。

因此,尽管这不是一个答案,但是如果您想节省一些时钟周期,我会采用类似的方法:

IntStream.range(0, 10)
          .boxed()
          .collect(Collectors.toMap(
              Function.identity(), 
              (x) -> IntStream.range(x * 10, x * 10 + 10)
          )) 

好像一个流是基于另一个流的,那么它总是必须具有完全相同的条目数。

但是,我找到了一个解决问题的方法:将消费者包装到“ GroupingConsumer”中。 这将终止初始流,但仍可以无限执行。

结果代码被截断:

// create a stream from 0 (inclusive) to infinity!
IntStream.iterate(0, i -> i+1).boxed()

// slow down
.peek((i) -> {try {Thread.sleep(50);} catch (InterruptedException e) {}})

// terminate the stream of single items (ungrouped)
.forEach(

    // create a wrap-around
    GroupingConsumer.create(

        // define the grouping rule
        i -> i/10,

        // the wrapped consumer
        System.out::println
)); 

GroupingConsumer类:

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Forwards a group of items, whenever the grouping-key changes
 *
 * @param <K> the type of the grouping key
 * @param <T> the type of the single entries
 */
class GroupingConsumer<K, T> implements Consumer<K> {

    private Function<K, T> keyCalculator;
    private Consumer<Entry<T, List<K>>> consumer;

    Entry<T, List<K>> currentGroup;

    /**
     * Wraps your consumer, so that it will get groups of items instead of single items.
     * 
     * @param keyCalculator the "grouping by"
     * @param consumer your consumer, that will be called less frequently
     * @return the wrapped consumer
     */
    public static <K, T> GroupingConsumer<K,T> create(Function<K, T> keyCalculator, Consumer<Entry<T, List<K>>> consumer) {
        GroupingConsumer<K, T> groupingConsumer = new GroupingConsumer<K, T>();
        groupingConsumer.consumer = consumer;
        groupingConsumer.keyCalculator = keyCalculator;
        return groupingConsumer;
    }

    @Override
    public void accept(K nextValue) {
        T key = keyCalculator.apply(nextValue);

        boolean newGroupRequired = false;

        if (currentGroup == null)
            newGroupRequired = true;
        else if (!currentGroup.getKey().equals(key)) {
            newGroupRequired = true;
            consumer.accept(currentGroup);
        }

        if (newGroupRequired)
            currentGroup = new SimpleEntry<T, List<K>>(key, new ArrayList<K>());
        currentGroup.getValue().add(nextValue);
    }
}

该功能在我的StreamEx库中可用,称为groupRuns :您可以根据提供的谓词将相邻元素收集到中间List中。 例:

IntStreamEx.iterate(0, i -> i+1).boxed().limit(100)
    .peek((i) -> {try {Thread.sleep(50);} catch (InterruptedException e) {}})
    .groupRuns((a, b) -> a/10 == b/10)
    .forEach(System.out::println);

您可以将数组视为具有键类型为int的Map,唯一的区别是,可以通过myArray[i]来查找值,而不是通过map.get(i)查找值。 使用数组对数组进行分组可让您避免按需装箱。 这是一种无需装箱即可产生相似结果的解决方案。

    int[][] results = IntStream.iterate(0, i -> i + 10)
            .limit(10)
            .mapToObj(i -> (int[]) IntStream.range(i, i + 10).toArray())
            .toArray(int[][]::new);

    System.out.println(Arrays.deepToString(results));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM