java stringjoiner_Java StringJoiner

Java StringJoiner

Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix and suffix to the char sequence.

import java.util.StringJoiner;

public class StringJoinerExample {

public static void main(String[] args) {

// passing comma(,) as delimiter

StringJoiner joinNames = new StringJoiner(",");

// Adding values to StringJoiner

joinNames.add("Rahul");

joinNames.add("Raju");

joinNames.add("Peter");

joinNames.add("Raheem");

System.out.println(joinNames);

// passing comma(,) and square-brackets as delimiter

StringJoiner joinNames2 = new StringJoiner(",", "[", "]");

// Adding values to StringJoiner

joinNames2.add("Rahul");

joinNames2.add("Raju");

joinNames2.add("Peter");

joinNames2.add("Raheem");

System.out.println(joinNames2);

StringJoiner joinNames3 = new StringJoiner(",", "[", "]");

joinNames3.add("Rahul");

joinNames3.add("Raju");

StringJoiner joinNames4 = new StringJoiner(":", "[", "]");

joinNames4.add("Peter");

joinNames4.add("Raheem");

// Merging two StringJoiner

StringJoiner merge = joinNames3.merge(joinNames4);

System.out.println(merge);

}

}

点击查看结果

```

Rahul,Raju,Peter,Raheem

[Rahul,Raju,Peter,Raheem]

[Rahul,Raju,Peter:Raheem]

```

import java.util.StringJoiner;

public class StringJoinerMethodExample {

public static void main(String[] args) {

StringJoiner joinNames = new StringJoiner(",");

// Prints nothing because it is empty

System.out.println(joinNames);

// We can set default empty value.

joinNames.setEmptyValue("It is empty");

System.out.println(joinNames);

// Adding values to StringJoiner

joinNames.add("Rahul");

joinNames.add("Raju");

System.out.println(joinNames);

// Returns length of StringJoiner

int length = joinNames.length();

System.out.println("Length: " + length);

// Returns StringJoiner as String type

String str = joinNames.toString();

System.out.println(str);

// Now, we can apply String methods on it

char ch = str.charAt(3);

System.out.println("Character at index 3: " + ch);

// Adding one more element

joinNames.add("Sorabh");

System.out.println(joinNames);

// Returns length

int newLength = joinNames.length();

System.out.println("New Length: " + newLength);

}

}

点击查看结果

```

It is empty

Rahul,Raju

Length: 10

Rahul,Raju

Character at index 3: u

Rahul,Raju,Sorabh

New Length: 17

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值