logo

Java에서 배열을 인쇄하는 방법

Java 배열은 동일한 데이터 유형의 요소를 저장할 수 있는 데이터 구조입니다. 배열의 요소는 인접한 메모리 위치에 저장됩니다. 따라서 고정된 요소 집합을 배열에 저장할 수 있습니다.

Java에서 배열을 인쇄하는 방법은 다음과 같습니다.

  • 자바 ~을 위한 고리
  • 자바 각각 고리
  • 자바 배열.toString() 방법
  • 자바 배열.deepToString() 방법
  • 자바 배열.asList() 방법
  • 자바 반복자 상호 작용
  • 자바 개울 API

자바 for 루프

자바 ~을 위한 루프는 특정 조건이 만족될 때까지 일련의 명령문을 반복적으로 실행하는 데 사용됩니다.

오픈 소스 OS의 예는 다음과 같습니다.

통사론:

 for(initialization; condition; increment/ decrement) { //statements } 

for 루프의 예

다음 예에서는 길이가 4인 배열을 만들고 그 안에 요소를 초기화했습니다. 배열에서 값을 가져오기 위해 for 루프를 사용했습니다. Java에서 배열을 인쇄하는 가장 널리 사용되는 방법입니다.

 public class PrintArrayExample1 { public static void main(String args[]) { //declaration and instantiation of an array int arr[]=new int[4]; //initializing elements arr[0]=10; arr[1]=20; arr[2]=70; arr[3]=40; //traversing over array using for loop for(int i=0;i <arr.length;i++) length is the property of array system.out.println(arr[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> 10 20 70 40 </pre> <h2>Java for-each loop</h2> <p>Java <strong>for-each</strong> loop is also used to traverse over an array or collection. It works on the basis of elements. It returns elements one by one in the defined variable. </p> <p> <strong>Syntax:</strong> </p> <pre> for(Type var:array) </pre> <p> <strong>Example of for-each loop</strong> </p> <p>In the following example, we have created an array of String type of length four and initialized elements into it. We have used for-each loop to traverse over the array.</p> <pre> public class PrintArrayExample2 { public static void main(String args[]) { // declaration and instantiation of an array String[] city = new String[4]; //initializing elements city[0] = &apos;Delhi&apos;; city[1] = &apos;Jaipur&apos;; city[2] = &apos;Gujarat&apos;; city[3] = &apos;Mumbai&apos;; //traversing over array using for-each loop for (String str : city) { System.out.println(str); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Delhi Jaipur Gujarat Mumbai </pre> <h2>Java Arrays.toString() method</h2> <p>Java <strong>Arrays.toString()</strong> is a static method of <strong>Arrays </strong> class which belongs to <strong>java.util </strong> package It contains various methods for manipulating array. </p> <p> <strong>Syntax:</strong> </p> <pre> public static String toString(int[] a) </pre> <p>It accepts an array of any primitive type as an argument. It returns a <strong>string</strong> representation of an array that contains a list of array&apos;s elements. The elements of an array are converted to String by <strong>String.valueOf(int) </strong> .</p> <p> <strong>Example of toString() method</strong> </p> <pre> import java.util.Arrays; public class PrintArrayExample3 { public static void main(String[] args) { //declaring and initializing array int array[] = {34,-10, 56, -9, -33}; //returns string representation of the specified array System.out.println(Arrays.toString(array)); } } </pre> <p> <strong>Output:</strong> </p> <pre> [34, -10, 56, -9, -33] </pre> <h2>Java Arrays.deepToString() method</h2> <p>The <strong>deepToString()</strong> method of Java Arrays class is designed for converting multidimensional arrays to strings.</p> <p> <strong>Syntax:</strong> </p> <pre> public static String deepToString(Object[] a) </pre> <p>It accepts an array as a parameter. It returns the String representation of an array.</p> <p> <strong>Example of deepToString() method</strong> </p> <p>In the following example, we have created a two dimensional array of float type. </p> <pre> import java.util.Arrays; public class PrintArrayExample4 { public static void main(String[] args) { //declaration and initialization of two dimensional array of float type float[][] array = {{1.2f, 2.5f}, {3.9f, 4.0f}, {5.3f, 6.2f}}; System.out.println(Arrays.deepToString(array)); } } </pre> <p> <strong>Output:</strong> </p> <pre> [[1.2, 2.5], [3.9, 4.0], [5.3, 6.2]] </pre> <h2>Java Arrays.asList() method</h2> <p>Java <strong>Arrays.asList()</strong> is a static method of Java <strong>Arrays</strong> class which belongs to <strong>java.util</strong> package. It act as a bridge between array based and collection based API. </p> <p> <strong>Syntax:</strong> </p> <pre> public static ListasList(T...a) </pre> <p>The method also provides an easy way to create a fixed-size list initialize to contain many elements.</p> <pre> List obj=Arrays.toString(array[] a </pre> <p>It accepts an array as an argument. It returns the list view of an array.</p> <p> <strong>Example of asList() method</strong> </p> <pre> import java.util.Arrays; public class PrintArrayExample5 { public static void main(String [] args) { //declaration and initialization of two dimensional array String[] stringArray={&apos;Hello&apos;,&apos;Java&apos;,&apos;Programmers&apos;}; System.out.println(Arrays.asList(stringArray)); } </pre> <p> <strong>Output:</strong> </p> <pre> [Hello, Java, Programmers] </pre> <h2>Java Iterator interface</h2> <p>Java <strong>Iterator</strong> is an interface which belongs to <strong>java.util</strong> package. The Iterator object can be created by calling iterator() method. It is present in Collection interface. It returns an iterator.</p> <p> <strong>Example of Iterator interface</strong> </p> <p>In the following, example, we have declare an array and initialize elements into it. We first convert the specified array into list by using Arrays.asList() method because iterator allows us to traverse over the collection and then invoke iterator() method of collection class.</p> <pre> import java.util.Arrays; import java.util.Iterator; public class PrintArrayExample6 { public static void main(String[] args) { //declaration and initialization of an array of Double type Double[] array = { 1.5, 2.6, 3.7, 4.8, 5.9}; //returns an iterator Iterator it = Arrays.asList(array).iterator(); while(itr.hasNext()) //returns a boolean value { System.out.println(itr.next()); } } } </pre> <p> <strong>Output:</strong> </p> <pre> 1.5 2.6 3.7 4.8 5.9 </pre> <h2>Java Stream API</h2> <p>A Java Stream is a data structure which is computed on-demand. It doesn&apos;t store data. It operates on the source data structure such as collection and array. Java stream API is used to implement internal iteration. It provides several features such as sequential and parallel execution. </p> <h3>Java stream() method</h3> <p>Java <strong>stream()</strong> is a static method of Java <strong>Arrays</strong> class which belongs to java.util package. It is used to get a sequential stream of an array.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Stream stream(T[] array) </pre> <p>Where <strong>T</strong> is the type of array. The method accepts an <strong>array</strong> whose elements are to be converted into a sequential stream. It returns a sequential <strong>IntStream</strong> with the specified array as its source.</p> <h3>Java forEach() method</h3> <p>It is a terminal operation. It does not guarantee to respect the encounter order of the stream.</p> <p> <strong>Syntax:</strong> </p> <pre> void forEach(Consumer action) </pre> <p>The method accepts an <strong>action</strong> as a parameter. It is non-interfering action perform on each element. It does not return anything.</p> <p>There are two terminal operations which we can apply to a stream to print an array.</p> <p> <strong>Get an iterator to the stream</strong> </p> <pre> Iterator it=Arrays.stream(arr).iterator(); </pre> <p> <strong>Using stream().forEach()</strong> </p> <pre> Arrays.stream(arr).forEach(System.out::println); </pre> <p> <strong>Example of stream.forEach() method</strong> </p> <p>In the following example, we have used a different way to print an array. The forEach() method is used to iterate over every element of the stream. It is defined in the Iterable and Stream interface.</p> <p>Inside the forEach() method we have used System.out which is a reference to an object. It represent standard output stream. It has a method called println(). It is an overloaded method which can accept anything as an argument. When we put println() method after member access operator (::), it becomes an expression.</p> <pre> import java.util.Arrays; public class PrintArrayExample7 { public static void main(String[] args) { //declaration and initialization of an array of String type String[] arr = {&apos;Java&apos;, &apos;C&apos;, &apos;C++&apos;, &apos;Python&apos;, &apos;Perl&apos;}; //iterating by passing the method reference Arrays.stream(arr).forEach(System.out::println); } } </pre> <p> <strong>Output:</strong> </p> <pre> Java C C++ Python Perl </pre> <hr></arr.length;i++)>

Java for-each 루프

자바 각각 루프는 배열이나 컬렉션을 순회하는 데에도 사용됩니다. 요소를 기반으로 작동합니다. 정의된 변수에 요소를 하나씩 반환합니다.

통사론:

 for(Type var:array) 

for-each 루프의 예

다음 예에서는 길이가 4인 문자열 유형의 배열을 만들고 그 안에 요소를 초기화했습니다. 배열을 순회하기 위해 for-each 루프를 사용했습니다.

 public class PrintArrayExample2 { public static void main(String args[]) { // declaration and instantiation of an array String[] city = new String[4]; //initializing elements city[0] = &apos;Delhi&apos;; city[1] = &apos;Jaipur&apos;; city[2] = &apos;Gujarat&apos;; city[3] = &apos;Mumbai&apos;; //traversing over array using for-each loop for (String str : city) { System.out.println(str); } } } 

산출:

 Delhi Jaipur Gujarat Mumbai 

자바 Arrays.toString() 메서드

자바 배열.toString() 정적 방법이다 배열 속한 클래스 java.util 패키지 배열을 조작하는 다양한 방법이 포함되어 있습니다.

통사론:

 public static String toString(int[] a) 

모든 기본 유형의 배열을 인수로 허용합니다. 그것은 배열의 요소 목록을 포함하는 배열의 표현입니다. 배열의 요소는 다음과 같이 문자열로 변환됩니다. 문자열.값(정수) .

toString() 메소드의 예

 import java.util.Arrays; public class PrintArrayExample3 { public static void main(String[] args) { //declaring and initializing array int array[] = {34,-10, 56, -9, -33}; //returns string representation of the specified array System.out.println(Arrays.toString(array)); } } 

산출:

 [34, -10, 56, -9, -33] 

Java Arrays.deepToString() 메서드

그만큼 deepToString() Java Arrays 클래스의 메소드는 다차원 배열을 문자열로 변환하도록 설계되었습니다.

통사론:

 public static String deepToString(Object[] a) 

배열을 매개변수로 받아들입니다. 배열의 문자열 표현을 반환합니다.

deepToString() 메소드의 예

다음 예에서는 float 유형의 2차원 배열을 만들었습니다.

 import java.util.Arrays; public class PrintArrayExample4 { public static void main(String[] args) { //declaration and initialization of two dimensional array of float type float[][] array = {{1.2f, 2.5f}, {3.9f, 4.0f}, {5.3f, 6.2f}}; System.out.println(Arrays.deepToString(array)); } } 

산출:

 [[1.2, 2.5], [3.9, 4.0], [5.3, 6.2]] 

자바 Arrays.asList() 메서드

자바 배열.asList() Java의 정적 메소드입니다. 배열 속한 클래스 java.util 패키지. 이는 배열 기반 API와 컬렉션 기반 API 사이의 브리지 역할을 합니다.

통사론:

 public static ListasList(T...a) 

이 메서드는 또한 많은 요소를 포함하도록 초기화되는 고정 크기 목록을 만드는 쉬운 방법을 제공합니다.

 List obj=Arrays.toString(array[] a 

배열을 인수로 받아들입니다. 배열의 목록 보기를 반환합니다.

asList() 메소드의 예

 import java.util.Arrays; public class PrintArrayExample5 { public static void main(String [] args) { //declaration and initialization of two dimensional array String[] stringArray={&apos;Hello&apos;,&apos;Java&apos;,&apos;Programmers&apos;}; System.out.println(Arrays.asList(stringArray)); } 

산출:

 [Hello, Java, Programmers] 

Java 반복자 인터페이스

자바 반복자 에 속하는 인터페이스입니다 java.util 패키지. Iterator 객체는 iterator() 메소드를 호출하여 생성할 수 있습니다. Collection 인터페이스에 존재합니다. 반복자를 반환합니다.

Iterator 인터페이스의 예

다음 예에서는 배열을 선언하고 배열 요소를 초기화했습니다. iterator를 사용하면 컬렉션을 순회한 다음 컬렉션 클래스의 iterator() 메서드를 호출할 수 있으므로 먼저 Arrays.asList() 메서드를 사용하여 지정된 배열을 목록으로 변환합니다.

 import java.util.Arrays; import java.util.Iterator; public class PrintArrayExample6 { public static void main(String[] args) { //declaration and initialization of an array of Double type Double[] array = { 1.5, 2.6, 3.7, 4.8, 5.9}; //returns an iterator Iterator it = Arrays.asList(array).iterator(); while(itr.hasNext()) //returns a boolean value { System.out.println(itr.next()); } } } 

산출:

 1.5 2.6 3.7 4.8 5.9 

자바 스트림 API

Java Stream은 주문형으로 계산되는 데이터 구조입니다. 데이터를 저장하지 않습니다. 컬렉션, 배열 등 소스 데이터 구조에서 작동합니다. Java 스트림 API는 내부 반복을 구현하는 데 사용됩니다. 순차 및 병렬 실행과 같은 여러 기능을 제공합니다.

자바 스트림() 메소드

자바 개울() Java의 정적 메소드입니다. 배열 java.util 패키지에 속하는 클래스입니다. 배열의 순차적 스트림을 얻는 데 사용됩니다.

통사론:

 public static Stream stream(T[] array) 

어디 배열 유형입니다. 이 방법은 정렬 그 요소는 순차 스트림으로 변환됩니다. 순차적으로 반환합니다. 인트스트림 지정된 배열을 소스로 사용합니다.

자바 forEach() 메소드

터미널 작업입니다. 스트림의 발생 순서를 존중한다는 보장은 없습니다.

통사론:

 void forEach(Consumer action) 

이 방법은 행동 매개변수로. 각 요소에 대해 수행되는 비간섭 작업입니다. 아무것도 반환하지 않습니다.

배열을 인쇄하기 위해 스트림에 적용할 수 있는 두 가지 터미널 작업이 있습니다.

스트림에 대한 반복자를 가져옵니다.

 Iterator it=Arrays.stream(arr).iterator(); 

stream().forEach() 사용

 Arrays.stream(arr).forEach(System.out::println); 

stream.forEach() 메소드의 예

다음 예에서는 배열을 인쇄하기 위해 다른 방법을 사용했습니다. forEach() 메서드는 스트림의 모든 요소를 ​​반복하는 데 사용됩니다. Iterable 및 Stream 인터페이스에 정의되어 있습니다.

forEach() 메소드 내에서 객체에 대한 참조인 System.out을 사용했습니다. 표준 출력 스트림을 나타냅니다. println()이라는 메소드가 있습니다. 이는 무엇이든 인수로 받아들일 수 있는 오버로드된 메서드입니다. 멤버 액세스 연산자(::) 뒤에 println() 메서드를 넣으면 표현식이 됩니다.

 import java.util.Arrays; public class PrintArrayExample7 { public static void main(String[] args) { //declaration and initialization of an array of String type String[] arr = {&apos;Java&apos;, &apos;C&apos;, &apos;C++&apos;, &apos;Python&apos;, &apos;Perl&apos;}; //iterating by passing the method reference Arrays.stream(arr).forEach(System.out::println); } } 

산출:

 Java C C++ Python Perl