簡體   English   中英

更改java.util.List的輸出類型

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

我創建了這個示例:

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

輸出:

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

為什么List的輸出總是用方括號打印數組形狀!

我的問題:我可以更改輸出類型,例如13 9 20 3 8 29 13 11 9 16還是其他形狀?

您可以使用正則表達式來做到這一點,但我不是專家。

這是自定義列表輸出的另一種方法。

創建一個將列表作為參數並輸出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;
}

輸出:

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

您還可以自定義:

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

輸出:

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

我會用一個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

輸出:

11 10 29 9 12 13 17 28 19 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM