java - Java - 连接流中的连续元素
问题描述
我正在尝试连接数组中的两个连续元素。我可以迭代地执行此操作,但我正在尝试学习 Java Streams,并认为这将是一个很好的练习。
如果我有一个字符串数组:
String exampleArray[] = ["a1", "junk", "a2", "b1", "junk", "b2", "c1", "junk", "junk", "junk", "c2", "d1", "junk", "d2", "junk-n"]
我想得到:
["a1 - a2", "b1 - b2", "c1 - c2", "d1 - d2"]
作为输出。
我试过这个:
Arrays.asList(exampleArray)
.stream()
.filter(s -> s.length() > 0) // gets rid of blanks
.filter(s -> !s.contains("junk"))
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2))
.values();
这会返回一个Collection<List<String>>
赞[ [a1, a2], [b1, b2], [c1, c2], [d1, d2] ]
但我不确定如何到达:["a1 - a2", "b1 - b2", "c1 - c2", "d1 - d2"]
任何帮助表示赞赏!
解决方案
Collectors.groupingBy has a overloaded method where you can pass the result to a downstream collector. In fact, by default it has used toList collector and so you got List. You can use joiningBy to concatenating strings.
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2
, Collectors.joining(" - ")))
Result is
[a1-a2, b1-b2, c1-c2, d1-d2]
Code
public static void main(String[] args) {
String exampleArray[] = new String[] {"a1", "junk", "a2", "b1", "junk", "b2", "c1", "junk", "junk", "junk", "c2", "d1", "junk", "d2", "junk-n"};
AtomicInteger counter = new AtomicInteger(0);
Collection<String> ans = (Arrays.asList(exampleArray)
.stream()
.filter(s -> s.length() > 0) // gets rid of blanks
.filter(s -> !s.contains("junk"))
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2, Collectors.joining(" - ")))
.values());
System.out.println(ans);
}