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 !!
My Question : Can I change type of the output like this 13 9 20 3 8 29 13 11 9 16
or another shape ?
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.
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 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.