使用定界符改变列表
Mutating the list using a delimiter
我有一个遵循这种形式 { a/b/c ; d/e/f ; ...}
的 ArrayList
,我想改变它并使其成为这种形式 { a ; b ; c ; d ; e ; ...}
。
我的意思是我知道我可以创建两个函数,一个负责删除 /
字符,另一个负责其余的。但我真的很好奇我是否可以使用一些内置函数来帮助我快速完成此操作。
好的,试一试:
List<String> purgedList = new ArrayList<>();
for (String s : listFromFile) {
purgedList.addAll(Arrays.asList(s.split("/")));
}
制作示例数据。
List < String > inputs = List.of( "a/b/c" , "d/e/f" , "g/h/i" );
创建一个空数组来放置结果。
List < String > result = new ArrayList <>( inputs.size() * 3 );
制作输入列表元素的流。
对于这些元素中的每一个,那些 String
个对象,调用 String#split
to produce an array of three separate String
object. Each of the three is the individual letter. Convert the array into a List
via List.of
。将该 String
个对象(字母)列表添加到我们的结果列表中。
inputs
.stream()
.forEach( s -> result.addAll( List.of( s.split( "/" ) ) ) );
转储到控制台。
System.out.println( "result = " + result );
可能有一种方法可以将结果列表创建折叠到流代码行中,类似于 。但我还不是 Streams Ninja。
最后,通常最好 return 一个不可修改的集合。调用 List.copyOf
.
return List.copyOf( result ) ;
试试这个。
public static void main(String[] args) {
List<String> input = List.of("a/b/c", "d/e/f", "g");
List<String> output = input.stream()
.flatMap(s -> Arrays.stream(s.split("/")))
.collect(Collectors.toList());
System.out.println(output);
}
看到这个code run live at IdeOne.com。
[a, b, c, d, e, f, g]
我有一个遵循这种形式 { a/b/c ; d/e/f ; ...}
的 ArrayList
,我想改变它并使其成为这种形式 { a ; b ; c ; d ; e ; ...}
。
我的意思是我知道我可以创建两个函数,一个负责删除 /
字符,另一个负责其余的。但我真的很好奇我是否可以使用一些内置函数来帮助我快速完成此操作。
好的,试一试:
List<String> purgedList = new ArrayList<>();
for (String s : listFromFile) {
purgedList.addAll(Arrays.asList(s.split("/")));
}
制作示例数据。
List < String > inputs = List.of( "a/b/c" , "d/e/f" , "g/h/i" );
创建一个空数组来放置结果。
List < String > result = new ArrayList <>( inputs.size() * 3 );
制作输入列表元素的流。
对于这些元素中的每一个,那些 String
个对象,调用 String#split
to produce an array of three separate String
object. Each of the three is the individual letter. Convert the array into a List
via List.of
。将该 String
个对象(字母)列表添加到我们的结果列表中。
inputs
.stream()
.forEach( s -> result.addAll( List.of( s.split( "/" ) ) ) );
转储到控制台。
System.out.println( "result = " + result );
可能有一种方法可以将结果列表创建折叠到流代码行中,类似于
最后,通常最好 return 一个不可修改的集合。调用 List.copyOf
.
return List.copyOf( result ) ;
试试这个。
public static void main(String[] args) {
List<String> input = List.of("a/b/c", "d/e/f", "g");
List<String> output = input.stream()
.flatMap(s -> Arrays.stream(s.split("/")))
.collect(Collectors.toList());
System.out.println(output);
}
看到这个code run live at IdeOne.com。
[a, b, c, d, e, f, g]