Java: convert List to a String

前端 未结 22 2603
日久生厌
日久生厌 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:50

    Three possibilities in Java 8:

    List list = Arrays.asList("Alice", "Bob", "Charlie")
    
    String result = String.join(" and ", list);
    
    result = list.stream().collect(Collectors.joining(" and "));
    
    result = list.stream().reduce((t, u) -> t + " and " + u).orElse("");
    

提交回复
热议问题