gpt4 book ai didi

java - 如何将字符串流转换为字符串流对?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:05:14 25 4
gpt4 key购买 nike

我想获取字符串流并将其转换为单词对流。例如:

我有:{ "A", "Apple", "B", "Banana", "C", "Carrot"}

我想要:{ ("A", "Apple"), ("Apple", "B"), ("B", "Banana"), ("Banana", "C") }

这与 Zipping 几乎相同,如 Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip) 中所述

但是,这会产生:{(A,苹果),(B,香蕉),(C,胡萝卜)}

下面的代码有效,但显然是错误的方法(不是线程安全的等等):

static String buffered = null;

static void output(String s) {
String result = null;
if (buffered != null) {
result = buffered + "," + s;
} else {
result = null;
}

buffered = s;
System.out.println(result);
}

// *****

Stream<String> testing = Stream.of("A", "Apple", "B", "Banana", "C", "Carrot");
testing.forEach(s -> {output(s);});

最佳答案

如果你:

  1. 不喜欢创建包含流中所有字符串的列表的想法
  2. 不想使用外部库
  3. 喜欢亲自动手

然后您可以创建一个方法来使用 Java 8 低级流构建器对流中的元素进行分组 StreamSupportSpliterator :

class StreamUtils {
public static<T> Stream<List<T>> sliding(int size, Stream<T> stream) {
return sliding(size, 1, stream);
}

public static<T> Stream<List<T>> sliding(int size, int step, Stream<T> stream) {
Spliterator<T> spliterator = stream.spliterator();
long estimateSize;

if (!spliterator.hasCharacteristics(Spliterator.SIZED)) {
estimateSize = Long.MAX_VALUE;
} else if (size > spliterator.estimateSize()) {
estimateSize = 0;
} else {
estimateSize = (spliterator.estimateSize() - size) / step + 1;
}

return StreamSupport.stream(
new Spliterators.AbstractSpliterator<List<T>>(estimateSize, spliterator.characteristics()) {
List<T> buffer = new ArrayList<>(size);

@Override
public boolean tryAdvance(Consumer<? super List<T>> consumer) {
while (buffer.size() < size && spliterator.tryAdvance(buffer::add)) {
// Nothing to do
}

if (buffer.size() == size) {
List<T> keep = new ArrayList<>(buffer.subList(step, size));
consumer.accept(buffer);
buffer = keep;
return true;
}
return false;
}
}, stream.isParallel());
}
}

方法和参数命名的灵感来自于它们在 Scala 中的对应项。

让我们测试一下:

Stream<String> testing = Stream.of("A", "Apple", "B", "Banana", "C", "Carrot");
System.out.println(StreamUtils.sliding(2, testing).collect(Collectors.toList()));

[[A, Apple], [Apple, B], [B, Banana], [Banana, C], [C, Carrot]]

关于不重复元素呢:

Stream<String> testing = Stream.of("A", "Apple", "B", "Banana", "C", "Carrot");
System.out.println(StreamUtils.sliding(2, 2, testing).collect(Collectors.toList()));

[[A, Apple], [B, Banana], [C, Carrot]]

现在有了无限的 Stream:

StreamUtils.sliding(5, Stream.iterate(0, n -> n + 1))
.limit(5)
.forEach(System.out::println);

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

关于java - 如何将字符串流转换为字符串流对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32162478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com