Arrays In Java

You already know that Array is a container which stores multiple values and the length of array will be fixed during declaration itself.

In this post let’s discuss Arrays of single dimensional, multi dimensional, Array’s functions etc.

One dimensional Array:  

long type:   long[] lng_arr = new long[3];
String type: String[] str_arr = new String[3];

similarly we can have arrays of other data types also. [byte[] anArrayOfBytes; short[]  anArrayOfShorts;  long[] anArrayOfLongs; float[] anArrayOfFloats;  double[] anArrayOfDoubles;  boolean[] anArrayOfBooleans;
char[] anArrayOfChars; String[] anArrayOfStrings;

Below is how we insert values to Array.

lng_arr[0] = 123; lng_arr[1] = 342; lng_arr[2] = 23;
str_arr [0] = "This"; str_arr [1] = "is"; str_arr [2] = "java_post"; 

You can also insert values to Array like given below. [giving values at the time of declaration itself]

long[] lng_arr = {123, 342, 23};
String[] str_arr = {"This", "is", "java_post"};

Now let’s see how we can print entire array itself. [using Arrays.toString(arr) we can achieve this]. For multi dimensional arrays we should use  Arrays.deepToString(arr).

System.out.println("lng_arr :"+lng_arr);  o/p: [J@3d04a311
System.out.println("lng_arr :"+Arrays.toString(lng_arr)); o/p: [123, 342, 23]
System.out.println("str_arr :"+Arrays.toString(str_arr)); o/p: [This,  is,  java_post]

Now let’s print single required value from the array: (for printing single value from the array, using of Arrays.toString(arr) is not required, which is used to print entire array in string foramt.

System.out.println("lng_arr[0] :"+lng_arr[0]);  o/p: 123
System.out.println("str_arr[2]:"+str_arr[2]);  o/p: java_post

Multi dimensional Array:  

long type:   long[][] lng_arr = new long[3][2];  
// [[a1, b1], [a2, b2], [a3, b3]]
(3 * 2) matrix would be like given below.
[a1, b1]
[a2, b2]
[a3, b3]
where [0][0] = a1;  [0][1] = b1;  [1][0] = a2;  [1][1] = b2;  [2][0] = a3;  [2][1] = b3; 

String type: String[][] str_arr = new String[2][3];  
// [[a1, b1,c1], [a2, b2, c2]]

similarly we can have arrays of other data types also. [byte[][] anArrayOfBytes; short[][]  anArrayOfShorts;  long[][] anArrayOfLongs; float[][] anArrayOfFloats;  double[][] anArrayOfDoubles;  boolean[][] anArrayOfBooleans;
char[][] anArrayOfChars; String[][] anArrayOfStrings;

Below is how we insert values to Array.

lng_arr[0][0] = 123;   lng_arr[0][1] = 342;    lng_arr[1][0] = 23;  lng_arr[1][1] = 223;  lng_arr[2][0] = 13;     lng_arr[2][1] = 323; 

str_arr [0][0] = “Mr. “;  str_arr [0][1] = “Mrs. “;    str_arr [0][2] = “Ms. “;  str_arr [1][0] = “Swamy “;  str_arr [1][1] = “Kumar”;    str_arr [1][2] = “Sita”; 

You can also insert values to Array like given below. [giving values at the time of declaration itself]

long[][] lng_arr = {{123, 342}, {23, 223}, {13, 323}};
String[][] str_arr = {{"Mr. ", "Mrs. ","Ms. "},{"Swamy","Kumar","Sita"}};

Now let’s see how we can print entire array itself. [using Arrays.deepToString(arr) we can achieve this].

System.out.println("lng_arr :"+Arrays.deepToString(lng_arr ));  
o/p: [[123, 342], [23,223], [13,323]]

System.out.println("str_arr :"+Arrays.deepToString(str_arr )); 
o/p: [[Mr. , Mrs. , Ms], [Swamy, Kumar, Sita]]

Now let’s print single required value from the array: (for printing single value from the array, using of Arrays.toString(arr) is not required, which is used to print entire array in string foramt.

System.out.println("lng_arr[0][1]:"+lng_arr[0][1]);  o/p: 342
System.out.println("str_arr[1][2]:"+str_arr[1][2]);  o/p:  sita

Arrays functions:  

Sort:   Sorting of Array can be achieved using Arrays.sort() method.

Given your array like below

long[] lng_arr = {18, 13, 23, 16, 20};
Arrays.sort(lng_arr);  
System.out.println("lng_arr:"+  Arrays.toString(lng_arr));  
o/p:  [13, 16, 18, 20, 23]

Sort some portion of Array: 

Sorting of Array can be achieved using Arrays.sort() method.

Given your array like below

long[] lng_arr = {18, 13, 23, 16, 20, 34, 12, 7};
Arrays.sort(lng_arr, 2, 5);  
System.out.println("lng_arr:"+  Arrays.toString(lng_arr)); 
o/p:  [18, 13, 16, 20, 23, 34  ,12, 7]

Get a value from array at specified index:

long[] lng_arr1 = {18, 13, 23, 16, 20, 34, 12, 7};
System.out.println(lng_arr1[4]);  // o/p:  20

Note: For list you need to use the get function.
List<Long> lst = new List<>();  
lst.add(27); lst.add(34); lst.add(23);
lst.get(1); //o/p: 34

To Print Entire Array: use Arrays.toString for one dimensional array and use  Arrays.deepToString for multi dimensional arrays and arrays converted from list.

long[] lng_arr1 = {18, 13, 23, 16, 20};
long[][] lng_arr2 = {{123, 342}, {23, 223}, {13, 323}};
System.out.println(Arrays.toString(lng_arr1)); 
System.out.println(Arrays.deepToString(lng_arr2));  
o/p:  [18, 13, 23, 16, 20]
[[123, 342], [23,223], [13,323]]

length: use length to find the length of an array.

long[] lng_arr = {18, 13, 23, 16, 20};
System.out.println(lng_arr.length);   o/p:  5

Note: To find the length of a list use size function.
List<Long> lst = new List<>();  
lst.add(27); lst.add(34); lst.add(23); 
lst.size(); //o/p: 3

To find the length of a string use length() function.
String val = "ravi";
System.out.println(val.length()); //o/p: 4

Happy Coding !

 

 

Advertisements

Sorting in Java

Sorting the numbers is easy in Java. Collections utility class provides the ‘sort’ method for sorting the numbers. [Don’t confuse with Collection which is an Interface]. To the Collections  Sort method you need to input numbers in List format. Though numbers present in Array also can be converted to List and then can be sorted. Java also provides another utility class ‘Arrays’ which has also Sort method. You can use either class methods for sorting on your convenience.

Collections.sort method expects List as input [array can also be send by converting to list object using Arrays.asList(arrayObj) method]

Arrays.sort method expects Array as input [List can also be send by converting to Array object using listObj.toArray() method]

Eg1: Sorting Numbers in List

List <Integer> numLst1 = new ArrayList<>();
numLst1.add(20);
numLst1.add(10);
numLst1.add(04);
Collections.sort(numLst1);
//Arrays.sort(numLst1.toArray());
int f = 0;
while(f< numLst1.size()){
System.out.println(numLst1.get(f));
f++;
}

o/p:   [4    10     20]

Eg2: Sorting Numbers in Array

Here we are converting Array to List and then sorting.

Integer[] numLst1 = {10, 30, 05};
Arrays.sort(numLst1);
//Collections.sort(Arrays.asList(numLst1));
int f = 0;
while(f<numLst1.length()){
System.out.println(numLst1[f].intValue());
f++;
}

o/p: [5    10     30]

Eg3: Sorting numbers and finding smallest number

Now let’s get into some deep by taking a requirement which returns the smallest number from the Array which should not be 0. Means if the Array contains numbers like [12, 20, 5, 30, 0, 50] then it should return smallest number as ‘5’ (not zero).

Integer[] returnVal = {10, 5, 20, 0};
Arrays.sort(returnVal);
//Collections.sort(Arrays.asList(returnVal));
int f= 0;
int smallValue = 0;
while(f < returnVal.length){
if (returnVal[f].intValue() !=0){
smallValue = returnVal[f].intValue();
break;
}
f++;
}
System.out.println("smallValue:"+smallValue);

o/p:   5

Sorting Numbers in HashSet & HashMap [not with the help of Sort method]

This can be achieved with the help of TreeSet. From TreeSet if you try to move to HashSet again then the insertion order will be lost. So keep the sorted result in TreeMap only or store them into LinkedHashSet where the insertion order is maintained. Similarly for HashMap sorting can be achieved with the help of TreeMap.


HashSet<Integer> hs = new HashSet<>();
hs.add(10);
hs.add(6);
hs.add(20);
hs.add(12);
System.out.println("hs:"+hs);
TreeSet<Integer> ts = new TreeSet<>();
ts.addAll(hs);
System.out.println("ts:"+ts);

o/p:     hs:[20, 6, 10, 12]      ts:[6, 10, 12, 20]