为了账号安全,请及时绑定邮箱和手机立即绑定

依次打印 ArrayList 中的所有字符

依次打印 ArrayList 中的所有字符

LEATH 2021-12-01 16:37:18
我有这个 ArrayListArrayList<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)
查看完整描述

3 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

Java 8 或更高版本:


final String result = wrongLetters.stream().map(String::valueOf).collect(Collectors.joining());

System.out.println("Number of errors: " + wrongLetters.size() + " (" +  result + ")");



查看完整回答
反对 回复 2021-12-01
?
弑天下

TA贡献1818条经验 获得超8个赞

从字符的数组列表中创建一个字符串


String str = "";

for (Character c : wrongLetters) {

    str += c;

然后 :


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

或制作一个字符串生成器:


StringBuilder stringBuilder= new StringBuilder(wrongLetters.size());


    for (Character c : wrongLetters) {

      stringBuilder.append(c);

    }

然后:


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



查看完整回答
反对 回复 2021-12-01
?
12345678_0001

TA贡献1802条经验 获得超5个赞

愚蠢的答案(只需删除非字母数字):


System.out.println("Number of errors: " + wrongLetters.size() + " (" + String.join("", String.valueOf(wrongLetters).replaceAll("[^A-Za-z0-9]", ""))+ ")");

Java 8+ 的另一个:


StringJoiner joiner = new StringJoiner("");

    wrongLetters.stream().forEach(err -> joiner.add(String.valueOf(err)));

    System.out.println("Number of errors: " + wrongLetters.size() + " (" + joiner + ")");

没有 Java 8(使用 StringBuilder):


StringBuilder sb = new StringBuilder(" (");

    for (Character character : wrongLetters) {

        sb.append(character);

    }

    sb.append(")");

    System.out.println("Number of errors: " + wrongLetters.size() + sb.toString());


查看完整回答
反对 回复 2021-12-01
  • 3 回答
  • 0 关注
  • 173 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信