java—连接流中的连续元素

kgqe7b3p  于 2021-07-05  发布在  Java
关注(0)|答案(3)|浏览(250)

我试图将数组中的两个连续元素连接起来。我可以迭代地这样做,但是我正在尝试学习java流,并且认为这将是一个很好的练习。
如果我有一个字符串数组: 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"] 感谢您的帮助!

of1yzvn4

of1yzvn41#

你差点就到了。你已经有一对了,现在你所要做的就是在中间用“-”把它们打成一根绳子。
试一试:

Arrays.stream(exampleArray)
                .filter(s -> s.length() > 0)   // gets rid of blanks
                .filter(s -> !s.contains("junk"))
                .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2))
                .values()
                .stream()                        //stream the pairs
                .map(l -> String.join("-", l))   //and put a "-" between them & into a string
                .collect(Collectors.toList())    //collect all your joined String
brc7rcf0

brc7rcf02#

实现此输出的简单方法是:

String a[] = {"a1", "junk", "a2", "b1", "junk", "b2", "c1", "junk", "junk", "junk", "c2", "d1", "junk", "d2", "junk-n"};

    Arrays.parallelSort(a); //sorting the array from a to z

    List<String> output = new ArrayList<>();

    for (int i = 0; i < a.length - 1; i++) {

        if(a[i].matches(".*\\d.*")) //verifying if have a number in string
           output.add(a[i] + " - " + a[++i]);

    }

    System.out.println(output); //["a1 - a2", "b1 - b2", "c1 - c2", "d1 - d2"]
l5tcr1uw

l5tcr1uw3#

collectors.groupingby有一个重载方法,您可以将结果传递给下游收集器。事实上,默认情况下,它使用了tolist收集器,所以您得到了list。可以使用joiningby连接字符串。

.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2
       , Collectors.joining(" - ")))

结果是

[a1-a2, b1-b2, c1-c2, d1-d2]

代码

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);
}

相关问题