简体   繁体   English

更改java.util.List的输出类型

[英]change type of the output of java.util.List

I created this example: 我创建了这个示例:

List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 10; i++) {
   list.add(new Random().nextInt(30) + 1);
}
System.out.println(list);

Output: 输出:

[13, 9, 20, 3, 8, 29, 13, 11, 9, 16]  // array shape

Why the List 's output always print array shape with square bracket !! 为什么List的输出总是用方括号打印数组形状!

My Question : Can I change type of the output like this 13 9 20 3 8 29 13 11 9 16 or another shape ? 我的问题:我可以更改输出类型,例如13 9 20 3 8 29 13 11 9 16还是其他形状?

You can do it using Regular Expressions but I'm not an expert. 您可以使用正则表达式来做到这一点,但我不是专家。

Here is another way to customize your list's output. 这是自定义列表输出的另一种方法。

Create a method that takes a list as a parameter and outputs a String. 创建一个将列表作为参数并输出String的方法。

public static void main(String[] args) throws java.lang.Exception {
    List<Integer> list = new ArrayList<Integer>();
    for(int i = 0; i < 10; i++) {
       list.add(new Random().nextInt(30) + 1);
    }
    System.out.println(formatMyList(list));
}

public static String formatMyList(List list){
    String str = list.toString().replace("[", "{");
    str = str.replace("]", "}");
    str = str.replace(",", " -");
    return str;
}

Output : 输出:

{25 - 20 - 12 - 25 - 18 - 11 - 17 - 23 - 22 - 29}

You can also customize : 您还可以自定义:

   public static String formatMyList(List list){
        String str = list.toString().replace("[", "I GOT ");
        str = str.replace("]", "!");
        str = str.replace(",", " AND");
        return str;
    }

Output : 输出:

I GOT 18 AND 22 AND 14 AND 16 AND 22 AND 21 AND 7 AND 14 AND 21 AND 14!

I would use a StringBuilder 我会用一个StringBuilder

StringBuilder sb = new StringBuilder();

for (int i: list) {
    sb.append(i + "\t");
}

System.out.println(sb.toString().trim());  //trim() to remove the last \t

Output: 输出:

11 10 29 9 12 13 17 28 19 3 11 10 29 9 12 13 17 28 19 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM