猿问

依次打印 ArrayList 中的所有字符

我有这个 ArrayList

ArrayList<Character> wrongLetters;

还有这个系统

System.out.println("Number of errors: " + wrongLetters.size() + " (" +  String.join("", String.valueOf(wrongLetters)) + ")");

它现在像这样打印

Number of errors: 9 ([X, M, S, K, B, Q, L, I, U])

但我怎样才能做到这样

Number of errors: 9 (XMSKBQLIU)


LEATH
浏览 174回答 3
3回答

皈依舞

Java 8 或更高版本:final String result = wrongLetters.stream().map(String::valueOf).collect(Collectors.joining());System.out.println("Number of errors: " + wrongLetters.size() + " (" +&nbsp; result + ")");

弑天下

从字符的数组列表中创建一个字符串String str = "";for (Character c : wrongLetters) {&nbsp; &nbsp; str += c;}&nbsp;然后 :System.out.println("Number of errors: " + wrongLetters.size() + " (" +&nbsp; String.join("", str) + ")");或制作一个字符串生成器:StringBuilder stringBuilder= new StringBuilder(wrongLetters.size());&nbsp; &nbsp; for (Character c : wrongLetters) {&nbsp; &nbsp; &nbsp; stringBuilder.append(c);&nbsp; &nbsp; }然后:&nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Number of errors: " + wrongLetters.size() + " (" +&nbsp; String.join("", stringBuilder.toString()) + ")");

12345678_0001

愚蠢的答案(只需删除非字母数字):System.out.println("Number of errors: " + wrongLetters.size() + " (" + String.join("", String.valueOf(wrongLetters).replaceAll("[^A-Za-z0-9]", ""))+ ")");Java 8+ 的另一个:StringJoiner joiner = new StringJoiner("");&nbsp; &nbsp; wrongLetters.stream().forEach(err -> joiner.add(String.valueOf(err)));&nbsp; &nbsp; System.out.println("Number of errors: " + wrongLetters.size() + " (" + joiner + ")");没有 Java 8(使用 StringBuilder):StringBuilder sb = new StringBuilder(" (");&nbsp; &nbsp; for (Character character : wrongLetters) {&nbsp; &nbsp; &nbsp; &nbsp; sb.append(character);&nbsp; &nbsp; }&nbsp; &nbsp; sb.append(")");&nbsp; &nbsp; System.out.println("Number of errors: " + wrongLetters.size() + sb.toString());
随时随地看视频慕课网APP

相关分类

Java
我要回答