我需要解析一个由不同整数组成的字符串,表示某个用户曾经或者没有看过电视的时间段。
我首先拆分字符串并将其收集到ArrayList:
final List<String> separated = stream(split(s, "A"))
.map(str -> "A" + str)
.flatMap(str -> stream(split(str, "B")).map(s2 -> s2.startsWith("A") ? s2 : "B" + s2))
collect(Collectors.toList());
现在有了棘手的事情。我需要将这些字符串转换为具有from/to
字段的域对象。
因此,为了正确映射,我的映射函数需要知道前一个元素。所以我做了以下事情:
LocalDateTime temp = initial;
final ArrayList<WatchingPeriod> result = new ArrayList<>();
for (final String s1 : separated) {
final WatchingPeriod period = new WatchingPeriod(temp, temp.plusMinutes(parseLong(substring(s1, 1))),
s1.startsWith("A"));
result.add(period);
temp = period.getTo();
}
return result;
我觉得这是一个巨大的退步,因为我打破整个流管道只是为了回到旧学校 - 每个人。
有什么办法可以在一个流管道中完成整个处理吗?我正在考虑创建一个自定义收集器,它将查看集合中的最后一个元素,并基于此计算正确的LocalDateTime对象。
示例:
输入字符串:&#34; A60B80A60&#34;,这意味着有人正在观看60分钟,然后停止观看80,然后再观看60分钟
因此我想获得一个包含对象的List:
1)从:0:00到:1:00,观看:真实
2)从:1:00到:2:20,看着:假
3)从:2:20到:3:20,看着:真实
每个对象的计算需要有关前一个对象的知识
答案 0 :(得分:4)
这不是关于连续对,而是关于收集累积前缀。在函数式编程中,这种操作通常称为scanLeft
,并且它存在于许多函数语言中,如Scala。不幸的是,它在Java 8 Stream API的当前实现中缺席,因此我们只能使用forEachOrdered
来模拟它。让我们创建一个模型对象:
static class WatchPeriod {
static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
final LocalTime start;
final Duration duration;
final boolean watched;
WatchPeriod(LocalTime start, Duration duration, boolean watched) {
this.start = start;
this.duration = duration;
this.watched = watched;
}
// Takes string like "A60" and creates WatchPeriod starting from 00:00
static WatchPeriod forString(String watchPeriod) {
return new WatchPeriod(LocalTime.of(0, 0),
Duration.ofMinutes(Integer.parseInt(watchPeriod.substring(1))),
watchPeriod.startsWith("A"));
}
// Returns new WatchPeriod which start time is adjusted to start
// right after the supplied previous period
WatchPeriod after(WatchPeriod previous) {
return new WatchPeriod(previous.start.plus(previous.duration), duration, watched);
}
@Override
public String toString() {
return "from: "+start.format(FORMATTER)+", to: "+
start.plus(duration).format(FORMATTER)+", watched: "+watched;
}
}
现在我们可以将输入字符串(如"A60B80A60"
)拆分为令牌"A60", "B80", "A60"
,将这些令牌映射到WatchPeriod
个对象,然后将它们存储到结果列表中:
String input = "A60B80A60";
List<WatchPeriod> result = new ArrayList<>();
Pattern.compile("(?=[AB])").splitAsStream(input)
.map(WatchPeriod::forString)
.forEachOrdered(wp -> result.add(result.isEmpty() ? wp :
wp.after(result.get(result.size()-1))));
result.forEach(System.out::println);
输出结果为:
from: 00:00, to: 01:00, watched: true
from: 01:00, to: 02:20, watched: false
from: 02:20, to: 03:20, watched: true
如果您不介意使用第三方库,我的免费StreamEx会增强Stream API,在其他功能中添加缺少scanLeft
操作:
String input = "A60B80A60";
List<WatchPeriod> result = StreamEx.split(input, "(?=[AB])")
.map(WatchPeriod::forString).scanLeft((prev, next) -> next.after(prev));
result.forEach(System.out::println);
结果是一样的。