如何在Java中将一个函数映射到字符串数组?

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

How should I map a function onto a string array in java?

问题

我想要分割一个字符串,并且修剪新建数组中的每个单词。在Java中是否有一种简单(函数式)的方法可以在不使用循环的情况下将其作为一行代码完成?

String[] stringarray = inputstring.split(";");
for (int i = 0; i < stringarray.length; i++) { 
    stringarray[i] = stringarray[i].trim(); 
}

编辑更正了循环Andreas的评论
英文:

I want to split a string and trim each word in the newly established array. Is there a simple (functional) way in Java how to do it as a one liner without the use of a cycle?

String[] stringarray = inputstring.split(&quot;;&quot;);
for (int i = 0; i &lt; stringarray.length; i++) { 
    stringarray[i] = stringarray[i].trim(); 
}

EDIT: corrected the cycle (Andreas' comment)

答案1

得分: 4

你可以按照以下方式进行操作:

String[] stringarray = inputstring.trim().split("\\s*;\\s*");

正则表达式解释:

  1. \s* 表示零个或多个空白字符
  2. \s*;\s* 表示零个或多个空白字符,后跟分号,然后可能跟零个或多个空白字符
英文:

You can do it in the following way:

String[] stringarray = inputstring.trim().split(&quot;\\s*;\\s*&quot;);

Explanation of the regex:

  1. \s* is zero or more times whitespace
  2. \s*;\s* specifies zero or more times whitespace followed by ; which may be followed by zero or more times whitespace

答案2

得分: 3

使用流,您可以这样做:

String[] stringarray = Arrays.stream(inputstring.split(";"))
            .map(String::trim)
            .toArray(String[]::new);
英文:

With streams you could do this:

String[] stringarray = Arrays.stream(inputstring.split(&quot;;&quot;))
        .map(String::trim)
        .toArray(String[]::new);

答案3

得分: 2

这可能不是纯粹的数组解决方案,而是一个Java 8解决方案:

String str = " string1 ;string2 ;string3 ;string4;";
String[] s = Arrays.stream(str.split(";")).map(String::trim).collect(Collectors.toList()).toArray(new String[]{});
System.out.println(Arrays.toString(s));
英文:

This may not be pure Array solution but a java 8 solution:

String str = &quot; string1 ;string2 ;string3 ;string4;&quot;;
String [] s = Arrays.stream(str.split(&quot;;&quot;)).map(String::trim).collect(Collectors.toList()).toArray(new String[]{});
System.out.println(Arrays.toString(s));

答案4

得分: 1

首先将数组转换为流(使用 Arrays 类),然后使用 map 函数,最后再转回数组。

https://mkyong.com/java8/java-8-how-to-convert-a-stream-to-array/

英文:

First convert the array to a stream (using the Arrays class), then use the map function, then convert back to array.

https://mkyong.com/java8/java-8-how-to-convert-a-stream-to-array/

huangapple
  • 本文由 发表于 2020年8月30日 23:44:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63659205.html
匿名

发表评论

匿名网友

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

确定