java list lt gt 用法,加入List< String>在Java中使用逗号和“和”

Given a list

List l = new ArrayList();

l.add("one");

l.add("two");

l.add("three");

I have a method

String join(List messages) {

if (messages.isEmpty()) return "";

if (messages.size() == 1) return messages.get(0);

String message = "";

message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");

message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");

return message;

}

which, for l, produces "one, two, and three".

My question is, is there a standard (apache-commons) method that does the same?, eg

WhatEverUtils.join(l, ", ", ", and ");

To clarify. My problem is not getting this method to work. It works just as I want it to, it's tested and all is well. My problem is that I could not find some apache-commons-like module which implements such functionality. Which surprises me, since I cannot be the first one to need this.

But then maybe everyone else has just done

StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");

解决方案

In Java 8 you can use String.join() like following:

Collection elements = ....;

String result = String.join(", ", elements);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值