我有这样的对象流:
"0", "1", "2", "3", "4", "5",如何将其转换为成对的流:
{ new Pair("0", "1"), new Pair("2", "3"), new Pair("4", "5")}.流大小未知。我正在从一个可能很大的文件中读取数据。我只有迭代器来收集,并且我使用分集器将这个迭代器转换为流。我知道这里有一个用StreamEx处理相邻对的答案:Collect successive pairs from a stream,这可以用java还是StreamEx来完成吗?谢谢
发布于 2018-02-28 11:18:53
如果你不想收集元素
问题的标题是从流中收集对,所以我假设您想实际收集这些,但是您评论了:
您的解决方案是可行的,问题是它将数据从文件加载到PairList,然后我可以使用来自这个集合的流来处理对。我做不到,因为数据可能太大,无法存储在内存中。
所以这里有一种方法可以做到这一点而不收集元素。
将Iterator,转换为Iterator相对简单,然后将流转换为成对的流。
/**
* Returns an iterator over pairs of elements returned by the iterator.
*
* @param iterator the base iterator
* @return the paired iterator
*/
public static <T> Iterator<List<T>> paired(Iterator<T> iterator) {
return new Iterator<List<T>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public List<T> next() {
T first = iterator.next();
if (iterator.hasNext()) {
return Arrays.asList(first, iterator.next());
} else {
return Arrays.asList(first);
}
}
};
}
/**
* Returns an stream of pairs of elements from a stream.
*
* @param stream the base stream
* @return the pair stream
*/
public static <T> Stream<List<T>> paired(Stream<T> stream) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(paired(stream.iterator()), Spliterator.ORDERED),
false);
}
@Test
public void iteratorAndStreamsExample() {
List<String> strings = Arrays.asList("a", "b", "c", "d", "e", "f");
Iterator<List<String>> pairs = paired(strings.iterator());
while (pairs.hasNext()) {
System.out.println(pairs.next());
// [a, b]
// [c, d]
// [e, f]
}
paired(Stream.of(1, 2, 3, 4, 5, 6, 7, 8)).forEach(System.out::println);
// [1, 2]
// [3, 4]
// [5, 6]
// [7, 8]
}如果你想收集元素..。
为此,我会将元素收集到列表中,并使用AbstractList作为对提供元素的视图。
首先是PairList。这是一个简单的AbstractList包装器,包含有偶数元素的任何列表。(一旦指定了所需的行为,就可以很容易地调整以处理奇数长度列表。)
/**
* A view on a list of its elements as pairs.
*
* @param <T> the element type
*/
static class PairList<T> extends AbstractList<List<T>> {
private final List<T> elements;
/**
* Creates a new pair list.
*
* @param elements the elements
*
* @throws NullPointerException if elements is null
* @throws IllegalArgumentException if the length of elements is not even
*/
public PairList(List<T> elements) {
Objects.requireNonNull(elements, "elements must not be null");
this.elements = new ArrayList<>(elements);
if (this.elements.size() % 2 != 0) {
throw new IllegalArgumentException("number of elements must have even size");
}
}
@Override
public List<T> get(int index) {
return Arrays.asList(elements.get(index), elements.get(index + 1));
}
@Override
public int size() {
return elements.size() / 2;
}
}然后我们可以定义我们需要的收集器。这本质上是collectingAndThen(toList(), PairList::new)的缩写
/**
* Returns a collector that collects to a pair list.
*
* @return the collector
*/
public static <E> Collector<E, ?, PairList<E>> toPairList() {
return Collectors.collectingAndThen(Collectors.toList(), PairList::new);
}请注意,为我们知道支持列表是新生成的用例(如本例中所示),定义一个不以防御方式复制列表的PairList构造函数可能是值得的。不过,现在还不是很重要。但是一旦我们这样做了,这个方法将是collectingAndThen(toCollection(ArrayList::new), PairList::newNonDefensivelyCopiedPairList)。
现在我们可以用它了
/**
* Creates a pair list with collectingAndThen, toList(), and PairList::new
*/
@Test
public void example() {
List<List<Integer>> intPairs = Stream.of(1, 2, 3, 4, 5, 6)
.collect(toPairList());
System.out.println(intPairs); // [[1, 2], [2, 3], [3, 4]]
List<List<String>> stringPairs = Stream.of("a", "b", "c", "d")
.collect(toPairList());
System.out.println(stringPairs); // [[a, b], [b, c]]
}下面是一个完整的源文件,其中包含一个可运行的示例(作为一个JUnit测试):
package ex;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
public class PairCollectors {
/**
* A view on a list of its elements as pairs.
*
* @param <T> the element type
*/
static class PairList<T> extends AbstractList<List<T>> {
private final List<T> elements;
/**
* Creates a new pair list.
*
* @param elements the elements
*
* @throws NullPointerException if elements is null
* @throws IllegalArgumentException if the length of elements is not even
*/
public PairList(List<T> elements) {
Objects.requireNonNull(elements, "elements must not be null");
this.elements = new ArrayList<>(elements);
if (this.elements.size() % 2 != 0) {
throw new IllegalArgumentException("number of elements must have even size");
}
}
@Override
public List<T> get(int index) {
return Arrays.asList(elements.get(index), elements.get(index + 1));
}
@Override
public int size() {
return elements.size() / 2;
}
}
/**
* Returns a collector that collects to a pair list.
*
* @return the collector
*/
public static <E> Collector<E, ?, PairList<E>> toPairList() {
return Collectors.collectingAndThen(Collectors.toList(), PairList::new);
}
/**
* Creates a pair list with collectingAndThen, toList(), and PairList::new
*/
@Test
public void example() {
List<List<Integer>> intPairs = Stream.of(1, 2, 3, 4, 5, 6)
.collect(toPairList());
System.out.println(intPairs); // [[1, 2], [2, 3], [3, 4]]
List<List<String>> stringPairs = Stream.of("a", "b", "c", "d")
.collect(toPairList());
System.out.println(stringPairs); // [[a, b], [b, c]]
}
}发布于 2018-02-28 11:03:19
这不是天生的适合,但你可以做到
List input = ...
List<Pair> pairs = IntStream.range(0, input.size() / 2)
.map(i -> i * 2)
.mapToObj(i -> new Pair(input.get(i), input.get(i + 1)))
.collect(Collectors.toList());要在流中创建对,您需要有状态的lambdas,这通常应该避免,但可以完成。注意:只有当流是单线程时才能工作。即不是平行的。
Stream<?> stream =
assert !stream.isParallel();
Object[] last = { null };
List<Pair> pairs = stream.map(a -> {
if (last[0] == null) {
last[0] = a;
return null;
} else {
Object t = last[0];
last[0] = null;
return new Pair(t, a);
}
}).filter(p -> p != null)
.collect(Collectors.toList());
assert last[0] == null; // to check for an even number input.发布于 2018-02-28 12:02:45
假设存在带有Pair的left、right和getter以及构造函数:
static class Paired<T> extends AbstractSpliterator<Pair<T>> {
private List<T> list = new ArrayList<>(2);
private final Iterator<T> iter;
public Paired(Iterator<T> iter) {
super(Long.MAX_VALUE, 0);
this.iter = iter;
}
@Override
public boolean tryAdvance(Consumer<? super Pair<T>> consumer) {
getBothIfPossible(iter);
if (list.size() == 2) {
consumer.accept(new Pair<>(list.remove(0), list.remove(0)));
return true;
}
return false;
}
private void getBothIfPossible(Iterator<T> iter) {
while (iter.hasNext() && list.size() < 2) {
list.add(iter.next());
}
}
}使用情况如下:
Iterator<Integer> iterator = List.of(1, 2, 3, 4, 5).iterator();
Paired<Integer> p = new Paired<>(iterator);
StreamSupport.stream(p, false)
.forEach(pair -> System.out.println(pair.getLeft() + " " + pair.getRight()));https://stackoverflow.com/questions/49027820
复制相似问题