J.Nemo

Stay Hungry, Stay Foolish

java打印数组内容的方法

循环打印

1
2
3
4
5
6
7
8
9
10
11
public void strTo() {
String[] s = new String[]{"乌鲁木齐", "兰州", "西安", "成都", "重庆"};
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length; i++) {
if (i > 0) {
stringBuilder.append(",");
}
stringBuilder.append(s[i]);
}
System.out.println(stringBuilder);
}

Arrays.toString() 打印

1
2
3
4
public void ArrsysTo() {
String[] s = new String[]{"乌鲁木齐", "兰州", "西安", "成都", "重庆"};
System.out.println(Arrays.toString(s));
}

JDK8 的 java.util.Arrays.stream() 打印

1
2
3
4
public void arraysStreamTo(){
String[] s = new String[]{"乌鲁木齐", "兰州", "西安", "成都", "重庆"};
Arrays.stream(s).forEach(System.out::print);
}

Arrays.deepToString() 方法打印

1
2
3
4
public void arraysDeepTo(){
String[] s = new String[]{"乌鲁木齐", "兰州", "西安", "成都", "重庆"};
System.out.println(Arrays.deepToString(s));
}

用list转化打印

1
2
3
4
5
6
public void listTo(){
String[] s = new String[]{"乌鲁木齐", "兰州", "西安", "成都", "重庆"};
List<String> list = new ArrayList<>();
Collections.addAll(list,s);
System.out.println(list);
}