Java – 连接流中的连续元素

huangapple go评论67阅读模式
英文:

Java - Concatenate Consecutive Elements in a Stream

问题

我正在尝试连接数组中连续的两个元素。我可以通过迭代来实现这一点,但我正在尝试学习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)   // 去除空白
	.filter(s -> !s.contains("junk"))
	.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2))
	.values();

这返回一个类似于 [ [a1, a2], [b1, b2], [c1, c2], [d1, d2] ]Collection<List<String>>

但我不知道如何得到:["a1 - a2", "b1 - b2", "c1 - c2", "d1 - d2"]

任何帮助都将不胜感激!

英文:

I am trying to concatenate two consecutive elements in an array. I could do this iteratively, but I am trying to learn Java Streams, and thought this would be a good exercise.

If I have an array of Strings:
String exampleArray[] = [&quot;a1&quot;, &quot;junk&quot;, &quot;a2&quot;, &quot;b1&quot;, &quot;junk&quot;, &quot;b2&quot;, &quot;c1&quot;, &quot;junk&quot;, &quot;junk&quot;, &quot;junk&quot;, &quot;c2&quot;, &quot;d1&quot;, &quot;junk&quot;, &quot;d2&quot;, &quot;junk-n&quot;]

I want to get:
[&quot;a1 - a2&quot;, &quot;b1 - b2&quot;, &quot;c1 - c2&quot;, &quot;d1 - d2&quot;] as output.

I tried this:

Arrays.asList(exampleArray)
	.stream()
	.filter(s -&gt; s.length() &gt; 0)   // gets rid of blanks
	.filter(s -&gt; !s.contains(&quot;junk&quot;))
	.collect(Collectors.groupingBy(it -&gt; counter.getAndIncrement() / 2))
	.values();

This returns a Collection&lt;List&lt;String&gt;&gt; like [ [a1, a2], [b1, b2], [c1, c2], [d1, d2] ]

But I am not sure how to get to: [&quot;a1 - a2&quot;, &quot;b1 - b2&quot;, &quot;c1 - c2&quot;, &quot;d1 - d2&quot;]

Any help is appreciated!

答案1

得分: 2

你已经接近成功了。你已经有了这些配对,现在你需要做的就是将它们用一个“-”连接起来,形成一个字符串。

试试这个:

Arrays.stream(exampleArray)
                .filter(s -> s.length() > 0)   // 去除空白
                .filter(s -> !s.contains("junk"))
                .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2))
                .values()
                .stream()                        // 流式处理配对
                .map(l -> String.join("-", l))   // 在它们之间加上“-”并组成一个字符串
                .collect(Collectors.toList())    // 收集所有连接后的字符串
英文:

You were almost there. You already had the pairs, all you have to do now is smash them with a "-" in the middle into a String.

Give this a try:

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

答案2

得分: 2

Collectors.groupingBy方法有一个重载的方法可以将结果传递给下游收集器事实上默认情况下它使用了toList收集器因此你会得到List<String>你可以使用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)   // 去除空白
                .filter(s -> !s.contains("junk"))
                .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2, Collectors.joining(" - ")))
                .values());
    
        System.out.println(ans);
    }
英文:

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<String>. You can use joiningBy to concatenating strings.

.collect(Collectors.groupingBy(it -&gt; counter.getAndIncrement() / 2
       , Collectors.joining(&quot; - &quot;)))

Result is

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

Code

public static void main(String[] args) {
    String exampleArray[] = new String[] {&quot;a1&quot;, &quot;junk&quot;, &quot;a2&quot;, &quot;b1&quot;, &quot;junk&quot;, &quot;b2&quot;, &quot;c1&quot;, &quot;junk&quot;, &quot;junk&quot;, &quot;junk&quot;, &quot;c2&quot;, &quot;d1&quot;, &quot;junk&quot;, &quot;d2&quot;, &quot;junk-n&quot;};
    AtomicInteger counter = new AtomicInteger(0);
    Collection&lt;String&gt; ans = (Arrays.asList(exampleArray)
            .stream()
            .filter(s -&gt; s.length() &gt; 0)   // gets rid of blanks
            .filter(s -&gt; !s.contains(&quot;junk&quot;))
            .collect(Collectors.groupingBy(it -&gt; counter.getAndIncrement() / 2, Collectors.joining(&quot; - &quot;)))
            .values());

    System.out.println(ans);
}

答案3

得分: 0

一个简单的方法来实现这个输出是:

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

Arrays.parallelSort(a); //对数组进行从小到大的排序

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

for (int i = 0; i < a.length - 1; i++) {
    if (a[i].matches(".*\\d.*")) //检查字符串中是否含有数字
        output.add(a[i] + " - " + a[++i]);
}

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

注意:由于您要求只返回翻译好的代码部分,以上即为代码的翻译部分。

英文:

A simple way to achieve this output is:

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

	Arrays.parallelSort(a); //sorting the array from a to z
	
	List&lt;String&gt; output = new ArrayList&lt;&gt;();
	
	for (int i = 0; i &lt; a.length - 1; i++) {
		
		if(a[i].matches(&quot;.*\\d.*&quot;)) //verifying if have a number in string
		   output.add(a[i] + &quot; - &quot; + a[++i]);
		
	}
	
	System.out.println(output); //[&quot;a1 - a2&quot;, &quot;b1 - b2&quot;, &quot;c1 - c2&quot;, &quot;d1 - d2&quot;]

huangapple
  • 本文由 发表于 2020年9月4日 08:54:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63733478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定