我有字符串项目列表,我正在尝试删除每个项目中的字符串部分,并使用它创建新列表。我可以使用下面的代码来实现它,但我认为将有一种使用流api处理此问题的更好方法。请让我知道是否有解决此问题的更好方法
请参见以下示例(简化说明)
List<String> list = new ArrayList<String>();
list.add("Value1.1,Value1.2,Value1.3,Value1.4,Value1.5,Value1.6");
list.add("Value2.1,Value2.2,Value2.3,Value2.4,Value2.5,Vaule2.6");
List<String> newList = list.stream().map(i -> {
List<String> l = Arrays.asList(i.split(","));
return StringUtils.join(ListUtils.sum(l.subList(0, 2),l.subList(4, l.size())),",");
}).collect(Collectors.toList());
newList.forEach(System.out::println);
// Value1.1,Value1.2,Value1.5,Value1.6
// Value2.1,Value2.2,Value2.5,Value1.6
Run Code Online (Sandbox Code Playgroud)
使用:org.apache.commons中的StringUtils,ListUtils
值1.1,值1.2,值1.5,值1.6
值2.1,值2.2,值2.5,值2.6
您可以使用正则表达式过滤掉不需要的值:
String pattern = "^([^,]*,[^,]*)(,[^,]*,[^,]*)(.*)$"
/** Explnation:
^ :start of line
(...) :group capture
[^,] :all characters which aren't ','
* :zero or more times
, :single comma
. :any character
$ :end of line
([^,]*,[^,]*) :first capture group ($1), two words seperated by ','
(,[^,]*,[^,]*) :second capture group ($2), the values we want to remove
(.*) :third capture group ($3), all the rest of the string
**/
Pattern patternCompiled = Pattern.compile(pattern);
List<String> newList = list.stream()
.map(i -> patternCompiled.matcher(i).replaceAll("$1$3"))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
96 次 |
最近记录: |