干货|如何用Java打印输出数组(Array)内容?代码示例!
在这篇文章里,我们将介绍5种用来打印输出java 数组内容的方法,并用代码示例。
使用 Arrays.toString() 打印数组内容
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 ]
使用循环语句打印java数组内容
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
使用 JDK 8 中的java.util.Arrays.stream() 打印
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
使用 Arrays.deepToString() 方法打印数组内容
这个 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]]
使用JDK 8中的Stream.flatMap( ) 打印数组
使用 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
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25