java 迭代取所有下级,Java Stream:有没有办法迭代一次取两个元素而不是一个?...

Let's say we have this stream

Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j");

and I want to save in a map the couples of adjacent strings in which the first one starts with "err".

What I thought of is something like this

Map map = new HashMap<>();

Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j")

.reduce((acc, next) -> {

if (acc.startsWith("err"))

map.put(acc,next);

if (next.startsWith("err"))

return next;

else

return "";

});

But I'm not totally satisfied with it for two main reasons

I'm "misusing" reduce function. In Stream API every function has its clear, well defined purpose: max is supposed to calcuate max value, filter is supposed to filter based on a condition, reduce is supposed to produce an incrementally accumulated value and so on.

Doing that prevents me from using Streams powerful mechanisms: what if I wanted to limit my search to the first two results?

Here I used reduce because (as far as I know) it's the only function that lets you compare couple of values that you can, somehow, lead back to something similar to "current value" and "next value" concepts.

Is there a more straightforward way? Something that allows you to iterate the stream considering more than one value for each iteration?

EDIT

What I'm thinking about is some mechanism that, given the current element, allows you to define a "window of elements" to consider, for each iteration.

Something like

Stream mapMoreThanOne(

int elementsBeforeCurrent,

int elementsAfterCurrent,

Function, ? extends R> mapper);

instead of

Stream map(Function super T, ? extends R> mapper);

That would be a powerful "upgrade" to current API.

EDIT2

I appreciate the effort of people proposing their solution, but the issue is not the algorithm per se. There are different ways to achieve my goal by putting together streams, indexes, temp variables to store previous values... but I was wondering if there was some method in Stream API that was designed for the task of dealing with elements other than the current without breaking the "stream paradigm". Something like this

List list =

Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j")

.filterFunctionImWonderingIfExist(/*filters couples of elements*/)

.limit(2)

.collect(Collectors.toList());

Given the answers, I think there's no "clear and quick" solution, unless using StreamEx library

解决方案

You can build a custom Collector for this task.

Map map =

Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j")

.collect(MappingErrors.collector());

with:

private static final class MappingErrors {

private Map map = new HashMap<>();

private String first, second;

public void accept(String str) {

first = second;

second = str;

if (first != null && first.startsWith("err")) {

map.put(first, second);

}

}

public MappingErrors combine(MappingErrors other) {

throw new UnsupportedOperationException("Parallel Stream not supported");

}

public Map finish() {

return map;

}

public static Collector> collector() {

return Collector.of(MappingErrors::new, MappingErrors::accept, MappingErrors::combine, MappingErrors::finish);

}

}

In this collector, two running elements are kept. Each time a String is accepted, they are updated and if the first starts with "err", the two elements are added to a map.

Another solution is to use the StreamEx library which provides a pairMap method that applies a given function to the every adjacent pair of elements of this stream. In the following code, the operation returns a String array consisting of the first and second element of the pair if the first element starts with "err", null otherwise. null elements are then filtered out and the Stream is collected into a map.

Map map =

StreamEx.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j")

.pairMap((s1, s2) -> s1.startsWith("err") ? new String[] { s1, s2 } : null)

.nonNull()

.toMap(a -> a[0], a -> a[1]);

System.out.println(map);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值