Open In App

Get Values with Unique Elements from a List in Java

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
// 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:

  • We have implemented a method i.e. hasRepeatedDigits() method to check whether the given number contains any repeated digits or not.
  • If no repeated digits found, then it will return false.
  • Then, we have implemented another method i.e. removeNumbersWithRepeatedDigits() to remove numbers with repeated digits from the original list.
  • After that in main method, we have created a list of numbers.
  • At last, we call removeNumbersWithRepeatedDigits() method and print the result to get a list of numbers with unique elements.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads