Java: convert List to a String

前端 未结 22 2635
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve

Does Java have anything

22条回答
  •  自闭症患者
    2020-11-22 01:57

    If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.

    List list = Arrays.asList("Bill", "Bob", "Steve");
    
    String string = ListAdapter.adapt(list).makeString(" and ");
    
    Assert.assertEquals("Bill and Bob and Steve", string);
    

    If you can convert your List to an Eclipse Collections type, then you can get rid of the adapter.

    MutableList list = Lists.mutable.with("Bill", "Bob", "Steve");
    String string = list.makeString(" and ");
    

    If you just want a comma separated string, you can use the version of makeString() that takes no parameters.

    Assert.assertEquals(
        "Bill, Bob, Steve", 
        Lists.mutable.with("Bill", "Bob", "Steve").makeString());
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题