将两个列表连接在一起,用 Java 中的逗号分隔

我有两个字符串列表(a 和 b),我想在每个元素后用逗号连接它们。我希望列表 a 的元素排在第一位。我也坚持使用 Java 7


我尝试了以下但它不起作用:


StringUtils.join(a, ", ").join(b, ", ");

这有效:


ArrayList<String> aAndB = new ArrayList<>();

aAndB.addAll(a);

aAndB.addAll(b);

StringUtils.join(aAndB, ", ");

有没有更短的方法来做到这一点?


芜湖不芜
浏览 154回答 4
4回答

大话西游666

您不需要StringUtils默认情况下List&nbsp;toString()以逗号分隔格式显示元素。System.out.println&nbsp;(new&nbsp;StringBuilder&nbsp;(aAndB.toString()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.deleteCharAt&nbsp;(aAndB.toString().length&nbsp;()-1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.deleteCharAt&nbsp;(0).toString&nbsp;());您唯一需要做的就是删除方括号

Smart猫小萌

由于您使用的是 Java 7,因此您可以编写一个静态方法来执行该任务。&nbsp; &nbsp; &nbsp; List<String> a = Arrays.asList("a", "b", "c");&nbsp; &nbsp; &nbsp; List<String> b = Arrays.asList("d", "e", "f");&nbsp; &nbsp; &nbsp; String s = join(",", a, b);&nbsp; &nbsp; &nbsp; System.out.println(s);&nbsp; &nbsp; &nbsp; List<Integer> aa = Arrays.asList(101, 102, 103);&nbsp; &nbsp; &nbsp; List<Integer> bb = Arrays.asList(104, 105, 106);&nbsp; &nbsp; &nbsp; String ss = join(":", aa, bb);&nbsp; &nbsp; &nbsp; System.out.println(ss);&nbsp; &nbsp;}&nbsp; &nbsp;public static <T> String join(String delimiter, List<T>... lists) {&nbsp; &nbsp; &nbsp; StringBuilder sb = new StringBuilder();&nbsp; &nbsp; &nbsp; for (List<T> list : lists) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (T item : list) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(delimiter);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(item);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return sb.substring(delimiter.length()).toString();&nbsp; &nbsp;}}这打印。a、b、c、d、e、f101:102:103:104:105:106

弑天下

要获得短代码,您可以:String&nbsp;res&nbsp;=&nbsp;String.join(",",&nbsp;a)&nbsp;+&nbsp;","&nbsp;+&nbsp;String.join(",",&nbsp;b);

翻翻过去那场雪

您可以像这样使用番石榴库:&nbsp; &nbsp; &nbsp; &nbsp; String [] a = {"a", "b", "c"};&nbsp; &nbsp; &nbsp; &nbsp; String [] b = {"d", "e"};&nbsp; &nbsp; &nbsp; &nbsp; //using Guava library&nbsp; &nbsp; &nbsp; &nbsp; String [] joined = ObjectArrays.concat(a, b, String.class);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Joined array : " + Arrays.toString(joined));&nbsp; &nbsp; &nbsp; &nbsp; // Output: "Joined array : [a, b, c, d, e]"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java