您可以
Collector为此任务建立自定义。
Map<String, String> map = Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j") .collect(MappingErrors.collector());与:
private static final class MappingErrors { private Map<String, String> 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<String, String> finish() { return map; } public static Collector<String, ?, Map<String, String>> collector() { return Collector.of(MappingErrors::new, MappingErrors::accept, MappingErrors::combine, MappingErrors::finish); }}在此收集器中,保留了两个运行元素。每次
String接受a时,它们都会更新,如果第一个以开头
"err",则会将这两个元素添加到地图中。
另一个解决方案是使用StreamEx库,该库提供一种
pairMap将给定功能应用于此流的每个相邻元素对的方法。在下面的代码中,如果第一个元素以开头
"err",
null则该操作将返回一个由该对的第一个和第二个元素组成的String数组。
null然后将元素过滤掉,并将Stream收集到地图中。
Map<String, String> 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);


