Java 8 – StringJoiner example

In this article, we will show you a few StringJoiner examples to join String.

1. StringJoiner
1.1 Join String by a delimiter


StringJoiner sj = new StringJoiner(",");
sj.add("aaa");
sj.add("bbb");
sj.add("ccc");
String result = sj.toString(); //aaa,bbb,ccc
1.2 Join String by a delimiter and starting with a supplied prefix and ending with a supplied suffix.


StringJoiner sj = new StringJoiner("/", "prefix-", "-suffix");
sj.add("2016");
sj.add("02");
sj.add("26");
String result = sj.toString(); //prefix-2016/02/26-suffix


2. String.join
StringJoiner is used internally by static String.join().

2.1 Join String by a delimiter.


//2015-10-31
String result = String.join("-", "2015", "10", "31" );
2.2 Join a List by a delimiter.


List<String> list = Arrays.asList("java", "python", "nodejs", "ruby");
//java, python, nodejs, ruby
String result = String.join(", ", list);


3. Collectors.joining
Two Stream and Collectors.joining examples.

3.1 Join List<String> example.


List<String> list = Arrays.asList("java", "python", "nodejs", "ruby");

//java | python | nodejs | ruby
String result = list.stream().map(x -> x).collect(Collectors.joining(" | "));
3.2 Join List<Object> example.


void test(){

List<Game> list = Arrays.asList(
new Game("Dragon Blaze", 5),
new Game("Angry Bird", 5),
new Game("Candy Crush", 5)
);

//{Dragon Blaze, Angry Bird, Candy Crush}
String result = list.stream().map(x -> x.getName())
.collect(Collectors.joining(", ", "{", "}"));

}

class Game{
String name;
int ranking;

public Game(String name, int ranking) {
this.name = name;
this.ranking = ranking;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getRanking() {
return ranking;
}

public void setRanking(int ranking) {
this.ranking = ranking;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值