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;
        }
    }

References

  1. Stream – Collectors.joining JavaDoc
  2. StringJoiner JavaDoc

如果觉得JSRUN的教程对您有用,请随意打赏。您的支持将鼓励JSRUN继续提供更好的服务

捐助JSRUN
JSRUN前端教程共编系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的本前端教程,让知识的积累变得统一完整、自成体系。 希望广大工程师能一起参与进共编,让零散在世界各处的知识点找到组织、找到家。
X
支付宝
9.99
请使用支付宝扫码支付, 有效时间 5分0秒
超过有效时间后请立即停止支付。
支付故障请联系QQ:565830900
因10.00元通道已占用,系统建议您支付9.99元
正在生成二维码, 此过程可能需要15秒钟
谢谢支持,我一定会更加努力的