加入具有不同最后分隔符的字符串 [英] Join strings with different last delimiter

查看:173
本文介绍了加入具有不同最后分隔符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 stream.collect(Collectors.joining(,))我可以轻松地加入逗号分隔的流的所有字符串。可能的结果是a,b,c。但是,如果我希望最后一个分隔符不同,该怎么办?例如,要,以便得到a,b和c作为结果。有一个简单的解决方案吗?

Using stream.collect(Collectors.joining(", ")) I can easily join all the strings of my stream delimited by a comma. A possible result would be "a, b, c". But what if I want the last delimiter to be different. For example to be " and " such that I get "a, b and c" as result. Is there an easy solution?

推荐答案

如果它们已经在列表中,则不需要流;只需加入除最后一个元素以外的所有元素的子列表,并连接另一个分隔符和最后一个元素:

If they are already in a list, no stream is needed; simply join a sublist of all but the last element and concat the other delimiter and the final element:

int last = list.size() - 1;
String joined = String.join(" and ",
                    String.join(", ", list.subList(0, last)),
                    list.get(last));

这是使用 Collectors.collectingAndThen执行上述操作的版本:

stream.collect(Collectors.collectingAndThen(Collectors.toList(),
    joiningLastDelimiter(", ", " and ")));

public static Function<List<String>, String> joiningLastDelimiter(
        String delimiter, String lastDelimiter) {
    return list -> {
                int last = list.size() - 1;
                if (last < 1) return String.join(delimiter, list);
                return String.join(lastDelimiter,
                    String.join(delimiter, list.subList(0, last)),
                    list.get(last));
            };
}

此版本还可以处理流为空或只有一个流的情况值。感谢Holger和Andreas的建议,这些建议极大地改善了这个解决方案。

This version can also handle the case where the stream is empty or only has one value. Thanks to Holger and Andreas for their suggestions which greatly improved this solution.

我在评论中建议使用,和作为分隔符,但会产生a和b的错误结果有两个元素,所以只是为了好玩,这是一个正确地使用牛津逗号:

I had suggested in a comment that the Oxford comma could be accomplished with this using ", " and ", and" as the delimiters, but that yields incorrect results of "a, and b" for two elements, so just for fun here's one that does Oxford commas correctly:

stream.collect(Collectors.collectingAndThen(Collectors.toList(),
    joiningOxfordComma()));

public static Function<List<String>, String> joiningOxfordComma() {
    return list -> {
                int last = list.size() - 1;
                if (last < 1) return String.join("", list);
                if (last == 1) return String.join(" and ", list);
                return String.join(", and ",
                    String.join(", ", list.subList(0, last)),
                    list.get(last));
            };
}

这篇关于加入具有不同最后分隔符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆