logo

Java'da dizi nasıl yazdırılır

Java dizisi aynı veri tipindeki elemanları saklayabileceğimiz bir veri yapısıdır. Bir dizinin elemanları bitişik bir bellek konumunda saklanır. Böylece bir dizide sabit bir öğe kümesini saklayabiliriz.

Java'da bir diziyi yazdırmanın aşağıdaki yolları vardır:

  • Java için döngü
  • Java her biri için döngü
  • Java Arrays.toString() yöntem
  • Java Arrays.deepToString() yöntem
  • Java Diziler.asList() yöntem
  • Java Yineleyici Arayüz
  • Java Aktarım API'si

Döngü için Java

Java için Döngü, belirli bir koşul sağlanana kadar bir dizi ifadeyi tekrar tekrar yürütmek için kullanılır.

java hashmap nedir

Sözdizimi:

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

For döngüsü örneği

Aşağıdaki örnekte, uzunluğu dört olan bir dizi oluşturduk ve bu diziye başlangıç ​​değerleri atanan öğeler oluşturduk. Diziden değer almak için for döngüsünü kullandık. Java'da dizi yazdırmanın en popüler yoludur.

 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++)>

Her döngü için Java

Java her biri için döngü aynı zamanda bir dizi veya koleksiyon üzerinde geçiş yapmak için de kullanılır. Elementler bazında çalışır. Tanımlanan değişkendeki elemanları birer birer döndürür.

Sözdizimi:

 for(Type var:array) 

Her biri için döngü örneği

Aşağıdaki örnekte, uzunluğu dört olan String tipinde bir dizi oluşturduk ve bu diziye başlangıç ​​değerleri atanan öğeler ekledik. Dizi üzerinde geçiş yapmak için for-each döngüsünü kullandık.

 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); } } } 

Çıktı:

 Delhi Jaipur Gujarat Mumbai 

Java Arrays.toString() yöntemi

Java Arrays.toString() statik bir yöntemdir Diziler ait olduğu sınıf java.util paket Diziyi işlemek için çeşitli yöntemler içerir.

Sözdizimi:

 public static String toString(int[] a) 

Herhangi bir ilkel türden bir diziyi argüman olarak kabul eder. Bir döndürür sicim Dizinin elemanlarının listesini içeren bir dizinin temsili. Bir dizinin elemanları şu şekilde String'e dönüştürülür: String.valueOf(int) .

toString() yöntemi örneği

 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)); } } 

Çıktı:

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

Java Arrays.deepToString() yöntemi

deepToString() Java Arrays sınıfının yöntemi, çok boyutlu dizileri dizelere dönüştürmek için tasarlanmıştır.

Sözdizimi:

 public static String deepToString(Object[] a) 

Bir diziyi parametre olarak kabul eder. Bir dizinin String gösterimini döndürür.

deepToString() yöntemi örneği

Aşağıdaki örnekte float tipinde iki boyutlu bir dizi oluşturduk.

 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)); } } 

Çıktı:

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

Java Arrays.asList() yöntemi

Java Diziler.asList() Java'nın statik bir yöntemidir Diziler ait olduğu sınıf java.util paket. Dizi tabanlı ve koleksiyon tabanlı API arasında köprü görevi görür.

Sözdizimi:

 public static ListasList(T...a) 

Yöntem aynı zamanda birçok öğeyi içerecek şekilde sabit boyutlu bir liste başlatma oluşturmanın kolay bir yolunu da sağlar.

 List obj=Arrays.toString(array[] a 

Bir diziyi argüman olarak kabul eder. Bir dizinin liste görünümünü döndürür.

asList() yöntemi örneği

 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)); } 

Çıktı:

 [Hello, Java, Programmers] 

Java Yineleyici arayüzü

Java Yineleyici ait bir arayüzdür java.util paket. Iterator nesnesi iterator() yöntemi çağrılarak oluşturulabilir. Koleksiyon arayüzünde bulunur. Bir yineleyici döndürür.

Yineleyici arayüzü örneği

Aşağıdaki örnekte, bir dizi tanımladık ve içindeki öğeleri başlattık. Yineleyici, koleksiyon üzerinde geçiş yapmamıza izin verdiğinden, önce Arrays.asList() yöntemini kullanarak belirtilen diziyi listeye dönüştürürüz ve ardından koleksiyon sınıfının iterator() yöntemini çağırırız.

 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()); } } } 

Çıktı:

 1.5 2.6 3.7 4.8 5.9 

Java Akışı API'si

Java Akışı, isteğe bağlı olarak hesaplanan bir veri yapısıdır. Verileri saklamaz. Koleksiyon ve dizi gibi kaynak veri yapısı üzerinde çalışır. Dahili yinelemeyi uygulamak için Java akışı API'si kullanılır. Sıralı ve paralel yürütme gibi çeşitli özellikler sağlar.

Java akışı () yöntemi

Java aktarım() Java'nın statik bir yöntemidir Diziler Java.util paketine ait olan sınıf. Bir dizinin sıralı akışını elde etmek için kullanılır.

Sözdizimi:

 public static Stream stream(T[] array) 

Nerede T dizi türüdür. Yöntem bir kabul eder sıralamak elemanları sıralı bir akışa dönüştürülecek. Sıralı bir şekilde döndürür İç Akış kaynağı olarak belirtilen diziyle.

Java forEach() yöntemi

Bu bir terminal operasyonudur. Akışın karşılaşma sırasına uyulacağını garanti etmez.

Sözdizimi:

 void forEach(Consumer action) 

Yöntem bir kabul eder aksiyon parametre olarak. Her öğe üzerinde müdahale etmeyen bir eylem gerçekleştirilir. Hiçbir şey döndürmez.

Bir diziyi yazdırmak için bir akışa uygulayabileceğimiz iki terminal işlemi vardır.

Akışa bir yineleyici alın

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

Stream().forEach() işlevini kullanma

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

Stream.forEach() yöntemi örneği

Aşağıdaki örnekte bir diziyi yazdırmak için farklı bir yol kullandık. forEach() yöntemi, akışın her öğesi üzerinde yineleme yapmak için kullanılır. Yinelenebilir ve Akış arayüzünde tanımlanır.

forEach() yönteminin içinde bir nesneye referans olan System.out'u kullandık. Standart çıktı akışını temsil eder. Println() adı verilen bir yöntemi vardır. Her şeyi argüman olarak kabul edebilen aşırı yüklenmiş bir yöntemdir. Println() metodunu üye erişim operatöründen (::) sonra koyduğumuzda bir ifadeye dönüşür.

 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); } } 

Çıktı:

 Java C C++ Python Perl