Open In App

Get Values with Unique Elements from a List in Java

In Java, we can write programs to get values with unique elements using loops, conditional statements, and string manipulation. The basic idea is to go through a set of numbers, check each number for repeating digits, eliminate them if any repeated number occurs, and print unique numbers from that list.

So, in this article, we will demonstrate how to get values with unique elements from a list by using loops and conditional statements.

Example Input Output:

Input: Original numbers list: [217, 429, 446, 199, 305, 667]

Output: Numbers with no repeating digits: [217, 429, 305]

Java Program to Get Values with Unique Elements from a List

// Java Program to Get Values with Unique Elements from a List  
import java.util.ArrayList;
import java.util.List;

public class GFG 
{
    // Method to check if a number contains repeating digits
    public static boolean hasRepeatedDigits(int num) 
    {
        boolean[] digits = new boolean[10];
        while (num > 0) 
        {
            int digit = num % 10;
            if (digits[digit]) 
            {
                return true;
            }
            digits[digit] = true;
            num /= 10;
        }
        return false; // If no repeating digits are found, return false
    }
    // Method to remove numbers with repeating digits from a list
    public static List<Integer> removeNumbersWithRepeatedDigits(List<Integer> numbers) {
        List<Integer> result = new ArrayList<>();
        for (int num : numbers) {
            if (!hasRepeatedDigits(num)) 
            {
                result.add(num);
            }
        }
        return result;
    }
    public static void main(String args[]) 
    {
        List<Integer> numbers = List.of(217, 429, 446, 199, 305, 667);
        System.out.println("Original Numbers list: " + numbers);
        List<Integer> result = removeNumbersWithRepeatedDigits(numbers);
        System.out.println("Numbers with Unique Digits: " + result);
    }
}

Output
Original Numbers list: [217, 429, 446, 199, 305, 667]
Numbers with Unique Digits: [217, 429, 305]

Explanation of the above Program:

Article Tags :