logo

Како штампати низ у Јави

Јава низ је структура података у којој можемо да складиштимо елементе истог типа података. Елементи низа се чувају на суседној меморијској локацији. Дакле, можемо да ускладиштимо фиксни скуп елемената у низу.

Постоје следећи начини за штампање низа у Јави:

  • Јава за петља
  • Јава за сваки петља
  • Јава Арраис.тоСтринг() методом
  • Јава Арраис.деепТоСтринг() методом
  • Јава Арраис.асЛист() методом
  • Јава Итератор Интерфејс
  • Јава Стреам АПИ

Јава фор петља

Јава за петља се користи за извршавање скупа исказа узастопно све док одређени услов није задовољен.

јавасцрипт коментар

Синтакса:

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

Пример фор петље

У следећем примеру, креирали смо низ дужине четири и иницијализовали елементе у њега. Користили смо фор петљу за преузимање вредности из низа. То је најпопуларнији начин за штампање низа у Јави.

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

Јава фор-еацх петља

Јава за сваки петља се такође користи за прелазак низа или колекције. Ради на основу елемената. Враћа елементе један по један у дефинисаној променљивој.

Синтакса:

 for(Type var:array) 

Пример за-сваке петље

У следећем примеру, креирали смо низ типа Стринг дужине четири и иницијализовали елементе у њега. Користили смо за-сваку петљу да пређемо низ низ.

 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 

Метод Јава Арраис.тоСтринг().

Јава Арраис.тоСтринг() је статичка метода Низови класа којој припада јава.утил пакет Садржи различите методе за манипулисање низом.

Синтакса:

 public static String toString(int[] a) 

Као аргумент прихвата низ било ког примитивног типа. Враћа а низ представљање низа који садржи листу елемената низа. Елементи низа се конвертују у Стринг помоћу Стринг.валуеОф(инт) .

Пример методе тоСтринг().

 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] 

Метод Јава Арраис.деепТоСтринг().

Тхе деепТоСтринг() метод класе Јава Арраис је дизајниран за претварање вишедимензионалних низова у стрингове.

Синтакса:

 public static String deepToString(Object[] a) 

Прихвата низ као параметар. Враћа стринг репрезентацију низа.

Пример методе деепТоСтринг().

У следећем примеру, креирали смо дводимензионални низ типа флоат.

 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]] 

Метод Јава Арраис.асЛист().

Јава Арраис.асЛист() је статичка метода Јаве Низови класа којој припада јава.утил пакет. Делује као мост између АПИ-ја заснованог на низу и збирки.

Синтакса:

 public static ListasList(T...a) 

Метод такође пружа једноставан начин да се иницијализира листа фиксне величине која садржи много елемената.

 List obj=Arrays.toString(array[] a 

Прихвата низ као аргумент. Враћа приказ листе низа.

Пример методе асЛист().

 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] 

Јава Итератор интерфејс

Јава Итератор је интерфејс који припада јава.утил пакет. Итератор објекат се може креирати позивањем методе итератор(). Присутан је у интерфејсу колекције. Враћа итератор.

Пример интерфејса Итератора

У следећем примеру, декларисали смо низ и иницијализовали елементе у њега. Прво конвертујемо наведени низ у листу коришћењем методе Арраис.асЛист() јер нам итератор омогућава да прелазимо преко колекције, а затим позовемо метод итератор() класе колекције.

 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 

Јава Стреам АПИ

Јава стреам је структура података која се израчунава на захтев. Не чува податке. Он ради на изворној структури података као што су збирка и низ. Јава стреам АПИ се користи за имплементацију интерне итерације. Пружа неколико функција као што су секвенцијално и паралелно извршавање.

Јава стреам() метода

Јава стреам() је статичка метода Јаве Низови класа која припада пакету јава.утил. Користи се за добијање секвенцијалног тока низа.

Синтакса:

 public static Stream stream(T[] array) 

Где Т је тип низа. Метод прихвата ан низ чији елементи треба да се конвертују у секвенцијални ток. Враћа секвенцијално ИнтСтреам са наведеним низом као извором.

Јава форЕацх() метода

То је терминална операција. То не гарантује поштовање редоследа сусрета у току.

Синтакса:

 void forEach(Consumer action) 

Метод прихвата ан поступак као параметар. То је акција која не омета сваки елемент. Не враћа ништа.

Постоје две терминалске операције које можемо применити на ток за штампање низа.

Набавите итератор за ток

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

Коришћење стреам().форЕацх()

 Arrays.stream(arr).forEach(System.out::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