在Java 8中流式处理时拆分逗号分隔的字符串值

4

我有一个String字段叫做userId,其中包含以逗号分隔的值,比如: String user = "123","456" 我想要拆分它。我已经编写了以下代码:

List<String> idList= employeeList.stream()
    .map(UserDto::getUserId)
    .filter(Objects::nonNull)
    .map(String::toUpperCase)
    .distinct()
    .collect(Collectors.toList());

这个 UserDto::getUserId 包含逗号分隔的值。在上述逻辑中是否可能进行分割。

谢谢

5个回答

4

我认为这应该有效

List<String> idList= employeeList.stream()
    .map(UserDto::getUserId)
    .filter(Objects::nonNull)
    .map(String::toUpperCase)
    .flatMap(s -> Arrays.stream(s.split(",")))//create a stream of split values
    .distinct()
    .collect(Collectors.toList());

谢谢你对那个优秀回答的评论。我也会对我的回答做出修改。 - Nithin

1

只需使用String的split(...)方法和flatMap(...),即可从数组流转换为数组内元素的流:

List<String> idList = employeeList.stream()
                .map(UserDto::getUserId)
                .filter(Objects::nonNull)
                .map(userId -> userId.split(",")) //get from the comma separated list to an array of elements
                .flatMap(Arrays::stream) //transform the stream of arrays to a stream of the elements inside the arrays
                .map(String::toUpperCase)
                .distinct()
                .collect(Collectors.toList());

1
可以使用 `
` 进行分割,类似于这样。
.map(ids -> ids.toUpperCase().split(","))

但是如果你想要创建一个带有ID的新列表,你可以尝试以下方法:
第一种解决方案

List<String> splitted = new ArrayList<>();
list.stream().filter(Objects::nonNull).forEach(it -> splitted.addAll(Arrays.asList(it.toUpperCase().split(","))));

第二个解决方案
list.stream().filter(Objects::nonNull).map(it -> Arrays.asList(it.toUpperCase().split(","))).flatMap(Collection::stream).collect(Collectors.toList());

0

这是它:

employeeList.stream()
.map(UserDto::getUserId)
.filter(Objects::nonNull)
.map(ids -> ids.split(","))
.flatMap(Arrays::stream)
.map(String::toUpperCase)
.distinct()
.collect(Collectors.toList());

看一下FlatMap的工作原理 ;)


不起作用。String::toUpperCase不适用于String[] - Johannes Kuhn

0
如果您需要频繁地进行拆分并且性能至关重要,或者按更复杂的规则进行拆分,例如按拆分并使用Pattern类删除空格,则应该考虑此方法:
Pattern splitter = Pattern.compile("\\s*,\\s*");
List<String> idList= employeeList.stream()
        .map(UserDto::getUserId)
        .filter(Objects::nonNull)
        .map(String::toUpperCase)
        .flatMap(s -> splitter.splitAsStream(s))
        .distinct()
        .collect(Collectors.toList());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接