Posts

Showing posts with the label Java Arrays

How to convert a Java list to an array

In this blog post, I will be explaining how you can convert a Java list to an array. To see how to convert an Array to a List, click here .   There are a couple of ways to do this. Consider the following code snippet: public class ListToArrayDemo {public static void main(String[] args) {//Method 1List<Integer> list = Arrays.asList(5,3,11,15,9);Object[] objects = list.toArray();//Method 2Integer[] integers = new Integer[list.size()];integers = list.toArray(integers);//Method 3Integer[] integers2 = new Integer[list.size()];for(int i = 0; i < list.size();i++){integers2[0] = list.get(0);}}} This code shows 3 ways to convert a List having integers to an array. Though I’ve used an Integer List here, you can use a List that stores any type of data. Method 1  The toArray method available on the list interface is used in this approach. This method returns an Object array. The downside to this approach is that the resultant array is an Object array. So you loose the type of d...

How to find the largest number in an array

The following code demonstrates how to find the largest number in an array:   package demo;public class LargestNumberDemo {public static void main(String[] args) {Integer[] intArr = {45,21,88,210,550,1,34};int max = 0;for(int num:intArr){if(num > max)max = num;}System.out.println("Biggest number is "+max);}}   So the for loop iterates through the array. Initially, the variable max is set to 0. Each number is compared with ‘max’ and if it is greater than max, then it is assigned to ‘max’. This process is repeated till all the elements in the array are exhausted.   This will print the following output: Biggest number is 550   You can use this code to find the largest number from any Collection type like Set or List.