w3resource

Java: Form the largest number from a given list of non negative integers


71. Find largest number from a list of non-negative integers

Write a Java program to find the largest number from a given list of non-negative integers.

Example:
Input :
nums = {1, 2, 3, 0, 4, 6}
Output:
Largest number using the said array numbers: 643210

Sample Solution:

Java Code:

// Import the necessary Java classes.
import java.util.*;

// Define the 'solution' class.
public class solution {

  // Define a method to find the largest number using an array of numbers.
  public static String largest_Numbers(int[] num) {
    // Convert the array of numbers to an array of strings.
    String[] array_nums = Arrays.stream(num).mapToObj(String::valueOf).toArray(String[]::new);
    
    // Sort the array of strings in descending order, considering their concatenated values.
    Arrays.sort(array_nums, (String str1, String str2) -> (str2 + str1).compareTo(str1 + str2));
    
    // Reduce the sorted array to find the largest number.
    return Arrays.stream(array_nums).reduce((a, b) -> a.equals("0") ? b : a + b).get();
  }	
	
  public static void main(String[] args)
  {
    // Initialize an array of numbers.
    int[] nums = {1, 2, 3, 0, 4, 6};
    
    // Print the original array and the largest number using the array elements.
    System.out.printf("\nOriginal array: " + Arrays.toString(nums));	
    System.out.printf("\nLargest number using the said array numbers: " + largest_Numbers(nums));
  }  
}

Sample Output:

Original array: [1, 2, 3, 0, 4, 6]
Largest number using the said array numbers: 643210

Flowchart:

Flowchart: Form the largest number from a given list of non negative integers.


For more Practice: Solve these Related Problems:

  • Write a Java program to find the smallest number possible from a given list of non-negative integers.
  • Write a Java program to find the largest number by rearranging digits of a given number.
  • Write a Java program to form the largest possible odd number using a given list of non-negative integers.
  • Write a Java program to form the smallest number using only the prime digits from a given list.

Go to:


PREV : Find smallest length subarray with sum >= specified value.
NEXT : Find continuous subarray to sort for array to be sorted.

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.