JOYLiuLiu 2018-07-05
在这篇文章里,我们将介绍5种用来打印输出java 数组内容的方法,并用代码示例。
package com.jackrutorial; import java.util.Arrays; public class PrintArrayExampleExample1 { public static void main (String [ ] args) { String [ ] programming Languages = new String [ ] {"Java", "Spring Boot", "Spring MVC", "AngularJS", "ReactJS", "Android"}; System.out.println (Arrays.to String ( programming Languages )); } }
输出
[ Java, Spring Boot, Spring MVC, AngularJS, ReactJS, Android ]
package com.jackrutorial; public class PrintArrayExampleExample2 { public static void main(String[] args) { String[ ] programmingLanguages = new String[ ] { "Java", "Spring Boot", "Spring MVC", "AngularJS", "ReactJS", "Android" }; StringBuffer strbf = new StringBuffer( ); for(int i = 0; i< programmingLanguages.length; i++) { if(i > 0) { strbf.append(", "); } strbf.append ( programmingLanguages[ i ]); } System.out.println( strbf ); } }
输出
Java, Spring Boot, Spring MVC, AngularJS, ReactJS, Android
package com.jackrutorial; import java.util.Arrays; public class PrintArrayExampleExample3 { public static void main(String[] args) { String[] programmingLanguages = new String [ ] {"Java", "Spring Boot", "Spring MVC", "AngularJS", "ReactJS", "Android"}; Arrays.stream(programmingLanguages).forEach(System.out::println); } }
输出
Java Spring Boot Spring MVC AngularJS ReactJS Android
这个 java.util.Arrays.deepToString(Object[ ])方法返回一个表达数组“内部内容”的字符串。如果数组中有其它数组,将会用同样的方法显示。
package com.jackrutorial; import java.util.Arrays; public class PrintArrayExampleExample4 { public static void main(String[] args) { String[ ][ ] programmingLanguages = {{"Java", "PHP", "C#"}, {"MySQL", "SQL", "Oracle"}}; System.out.println(Arrays.deepToString(programmingLanguages)); } }
输出
[[Java, PHP, C#], [MySQL, SQL, Oracle]]
使用 Stream.flatMap( )我们可以输出多维数组。
package com.jackrutorial; import java.util.Arrays; public class PrintArrayExampleExample5 { public static void main(String[] args) { String[ ][ ] programmingLanguages = {{"Java", "PHP", "C#"}, {"MySQL", "SQL", "Oracle"}}; Arrays.stream(programmingLanguages).flatMap(x -> Arrays.stream(x)).forEach(System.out::println); } }
输出
Java PHP C# MySQL SQL Oracle