使用Java 8 Streams API随机整理整数列表

问题描述 投票:26回答:8

我尝试使用Streams API将以下Scala行转换为Java 8:

// Scala
util.Random.shuffle((1 to 24).toList)

要编写等效的Java语言,我创建了一个整数范围:

IntStream.range(1, 25)

我怀疑在流API中找到了toList方法,但是IntStream只知道奇怪的方法:

collect(
  Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)

如何使用Java 8 Streams API随机播放列表?

java scala java-stream
8个回答
31
投票

您在这里:

List<Integer> integers =
    IntStream.range(1, 10)                      // <-- creates a stream of ints
        .boxed()                                // <-- converts them to Integers
        .collect(Collectors.toList());          // <-- collects the values to a list

Collections.shuffle(integers);

System.out.println(integers);

打印:

[8, 1, 5, 3, 4, 2, 6, 9, 7]

26
投票

您可能会发现以下toShuffledList()方法很有用。

private static final Collector<?, ?, ?> SHUFFLER = Collectors.collectingAndThen(
        Collectors.toCollection(ArrayList::new),
        list -> {
            Collections.shuffle(list);
            return list;
        }
);

@SuppressWarnings("unchecked")
public static <T> Collector<T, ?, List<T>> toShuffledList() {
    return (Collector<T, ?, List<T>>) SHUFFLER;
}

这将启用以下一种单线:

IntStream.rangeClosed('A', 'Z')
         .mapToObj(a -> (char) a)
         .collect(toShuffledList())
         .forEach(System.out::print);

示例输出:

AVBFYXIMUDENOTHCRJKWGQZSPL

7
投票

您可以使用一个自定义比较器,该比较器将这些值按随机值“排序”:

public final class RandomComparator<T> implements Comparator<T> {

    private final Map<T, Integer> map = new IdentityHashMap<>();
    private final Random random;

    public RandomComparator() {
        this(new Random());
    }

    public RandomComparator(Random random) {
        this.random = random;
    }

    @Override
    public int compare(T t1, T t2) {
        return Integer.compare(valueFor(t1), valueFor(t2));
    }

    private int valueFor(T t) {
        synchronized (map) {
            return map.computeIfAbsent(t, ignore -> random.nextInt());
        }
    }

}

流中的每个对象都(延迟地)关联了一个随机整数值,我们对其进行排序。地图上的同步用于处​​理并行流。

然后您可以像这样使用它:

IntStream.rangeClosed(0, 24).boxed()
    .sorted(new RandomComparator<>())
    .collect(Collectors.toList());

此解决方案的优点是它集成在流管道中。


2
投票

如果您希望处理整个Stream时没有太多麻烦,则可以使用Collectors.collectingAndThen()创建您自己的收集器:

public static <T> Collector<T, ?, Stream<T>> toEagerShuffledStream() {
    return Collectors.collectingAndThen(
      toList(),
      list -> {
          Collections.shuffle(list);
          return list.stream();
      });
}

但是如果您要limit()生成的流,这将不能很好地执行。为了克服这个问题,可以创建一个自定义的Spliterator:

package com.pivovarit.stream;

import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.RandomAccess;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Supplier;

class ImprovedRandomSpliterator<T, LIST extends RandomAccess & List<T>> implements Spliterator<T> {

    private final Random random;
    private final List<T> source;
    private int size;

    ImprovedRandomSpliterator(LIST source, Supplier<? extends Random> random) {
        Objects.requireNonNull(source, "source can't be null");
        Objects.requireNonNull(random, "random can't be null");

        this.source = source;
        this.random = random.get();
        this.size = this.source.size();
    }

    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        if (size > 0) {
            int nextIdx = random.nextInt(size);
            int lastIdx = --size;

            T last = source.get(lastIdx);
            T elem = source.set(nextIdx, last);
            action.accept(elem);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Spliterator<T> trySplit() {
        return null;
    }

    @Override
    public long estimateSize() {
        return source.size();
    }

    @Override
    public int characteristics() {
        return SIZED;
    }
}

然后:

public final class RandomCollectors {

    private RandomCollectors() {
    }

    public static <T> Collector<T, ?, Stream<T>> toImprovedLazyShuffledStream() {
        return Collectors.collectingAndThen(
          toCollection(ArrayList::new),
          list -> !list.isEmpty()
            ? StreamSupport.stream(new ImprovedRandomSpliterator<>(list, Random::new), false)
            : Stream.empty());
    }

    public static <T> Collector<T, ?, Stream<T>> toEagerShuffledStream() {
        return Collectors.collectingAndThen(
          toCollection(ArrayList::new),
          list -> {
              Collections.shuffle(list);
              return list.stream();
          });
    }
}

我在这里解释了性能注意事项:https://4comprehension.com/implementing-a-randomized-stream-spliterator-in-java/


1
投票

要有效执行随机播放,您需要事先提供所有值。将流转换为列表后,可以像在Scala中一样使用Collections.shuffle()。


1
投票
public static List<Integer> getSortedInRandomOrder(List<Integer> list) {
    return list
            .stream()
            .sorted((o1, o2) -> ThreadLocalRandom.current().nextInt(-1, 2))
            .collect(Collectors.toList());
}

0
投票

[如果您正在寻找“仅流式”解决方案,并且确定性,仅“偶然”排序与“随机”排序就足够了,那么您始终可以通过哈希值对int进行排序:

List<Integer> xs=IntStream.range(0, 10)
    .boxed()
    .sorted( (a, b) -> a.hashCode() - b.hashCode() )
    .collect(Collectors.toList());

[如果您想拥有int[]而不是List<Integer>,则可以随后将其取消装箱。不幸的是,您已经经历了装箱步骤,以应用自定义Comparator,因此没有消除过程的这一部分。

List<Integer> ys=IntStream.range(0, 10)
    .boxed()
    .sorted( (a, b) -> a.hashCode() - b.hashCode() )
    .mapToInt( a -> a.intValue())
    .toArray();

-2
投票

这是我的单行解决方案:我正在选择一种随机颜色:

colourRepository.findAll().stream().sorted((o1,o2)-> RandomUtils.nextInt(-1,1)).findFirst().get()
© www.soinside.com 2019 - 2024. All rights reserved.