6

我有一个字符串列表,例如"/100" "/100/200". 我希望将这些字符串拆分为/,然后得到一个整数列表列表,例如[[100],[100,200]]. 如果该列表足够长,我想遍历这个列表并从每个列表中获取第 n 个元素,否则移动到下一个列表。

众所周知,每个内部列表都是最大长度n

例子 :

n= 3
slashString -> "/100/200/300","/200/300","/100/200/400"

在上述情况下,我想要一个整数列表作为300,400.

List<Integer> output = slashString.stream()
        .map(x->Arrays.stream(x.split("/")).collect(Collectors.toList()))
        .filter(x->x.size()==3)

我能想到上面。我最终将如何收集所有整数列表中的第三个元素。

4

4 回答 4

4

只需将每个元素映射ListList并收集的第三个元素:

List<Integer> list = Stream.of ("100/200/300","200/300","100/200/400")
    .map(x->Arrays.stream(x.split("/")).collect(Collectors.toList()))
    .filter(x->x.size()==3)
    .map(l->Integer.valueOf (l.get(2)))
    .collect(Collectors.toList());

请注意,您必须消除/输入Strings 的前导。否则第 1 和第 3 的长度List将是 4,并且它们不会通过过滤器。或者您可以要求List尺寸为 4 而不是 3(并更改l.get(2)l.get(3))。

于 2018-07-08T07:57:43.187 回答
4

你快到了。

过滤大小为 3 的列表后,获取第三个元素并将其转换为 Integer。

另外,请注意拆分 String/100/200会给您一个String[]( ["", "100", "200"]) ,其中第一个元素是空字符串。所以,我跳过了第一个元素skip(1)

List<Integer> result = slashString.stream()
            .map(x-> Arrays.stream(x.split("/"))
                    .skip(1)
                    .collect(Collectors.toList()))
            .filter(x -> x.size() >= 3)
            .map(list -> Integer.valueOf(list.get(2)))
            .collect(Collectors.toList());
于 2018-07-08T08:00:29.467 回答
4

Remove all but the third term using regex, filter out empties, voila!

List<Integer> list = Stream.of("100/200/300", "200/300", "100/200/400")
    .map(s -> s.replaceAll("^([^/]/[^/]/)?([^/]+)?(/.*)?", "$2"))
    .filter(s -> !s.isEmpty())
    .map(Integer::valueOf)
    .collect(Collectors.toList());

The regex always matches the whole string, and replaces it with the 3rd term, which was captured as group 2, but because everything is optional, group 2 (the final result) is blank if there isn’t a 3rd term.

This approach only ever deals with Strings, which keeps things simpler by avoiding ugly array code.

于 2018-07-08T08:19:38.287 回答
3

您不需要制作中间列表。而是将每个字符串转换为一个空流或仅包含第 n 个元素的流,skip(n).limit(1)并用于flatMap将所有小流合并在一起:

Pattern delimiter = Pattern.compile("/");
int n = 3;

List<Integer> result = slashString.stream()
        .flatMap(s -> delimiter.splitAsStream(s).skip(n).limit(1))
        .map(Integer::valueOf)
        .collect(toList());
于 2018-07-08T10:13:34.180 回答