Java代码打印数组的方法大全
下文笔者讲述使用java代码打印数组的方法大全,如下所示
打印数组的方法大全: 方式1: 借助Arrays.toString对数组进行转换,然后打印数组 方式2: 将数组转换为stream,然后打印输出 方式3: 使用JSON的方式打印数组
Arrays.toString打印数组
package com.java265.utils.print; import java.util.Arrays; public class PrintArray { public static void main(String[] args) { // array String[] arrayStr = new String[]{"Java", "Node", "Python", "Ruby"}; System.out.println(Arrays.toString(arrayStr)); int[] arrayInt = {1, 3, 5, 7, 9}; System.out.println(Arrays.toString(arrayInt)); // 2d array, need Arrays.deepToString String[][] deepArrayStr = new String[][]{{"java2651", "java2652"}, {"java2653", "java2654"}}; System.out.println(Arrays.toString(deepArrayStr)); System.out.println(Arrays.deepToString(deepArrayStr)); int[][] deepArrayInt = new int[][]{{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}}; System.out.println(Arrays.toString(deepArrayInt)); System.out.println(Arrays.deepToString(deepArrayInt)); } }
借助jdk8中的Stream打印数组
package com.java265.utils.print; import java.util.Arrays; public class PrintArray { public static void main(String[] args) { // array String[] arrayStr = new String[]{"Java", "Node", "Python", "Ruby"}; Arrays.stream(arrayStr).forEach(System.out::println); int[] arrayInt = {23,22,67,89,110}; Arrays.stream(arrayInt).forEach(System.out::println); //2d array String[][] deepArrayStr = new String[][]{{"java2651", "java2652"}, {"java2653", "java2654"}}; Arrays.stream(deepArrayStr).flatMap(x -> Arrays.stream(x)).forEach(System.out::println); int[][] deepArrayInt = new int[][]{{23,22,67,89,110}, {3,6,8,9}}; Arrays.stream(deepArrayInt).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println); } }
使用Gson的方式打印数组
PrintUtils.java package com.java265.utils.print; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class PrintUtils { private static final ObjectMapper om = new ObjectMapper(); public static void print(Object object) { String result; try { result = om.writerWithDefaultPrettyPrinter().writeValueAsString(object); System.out.println(result); } catch (JsonProcessingException e) { e.printStackTrace(); } } } PrintArray.java package com.java265.utils.print; public class PrintArray { public static void main(String[] args) { //array String[] arrayStr = new String[]{"Java", "Node", "Python", "Ruby"}; PrintUtils.print(arrayStr); int[] arrayInt = {23,22,67,89,110}; PrintUtils.print(arrayInt); //2d array String[][] deepArrayStr = new String[][]{{"java2651", "java2652"}, {"java2653", "java2654"}}; PrintUtils.print(deepArrayStr); int[][] deepArrayInt = new int[][]{{23,22,67,89,110}, {88,12,34,56,87}}; PrintUtils.print(deepArrayInt); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。