-1

Suppose in an array, there is the numbers {1,1,1,1,1,5} How do I write a program that does not specifically relate to the numbers(ex. no printing {1,5}) that gets rid of all the repeating numbers in this array?

In other words, if the problem was {a,b,c,d,e} and I without me knowing the numbers inside, how do I write a program in Java that gets rid of all the repeating digits?(the example on the very top's answer would be {1,5})

1 Answers1

-1

If you want to keep only unique element you can use a set.

// Generic function to convert list to set 
    public static <T> Set<T> convertListToSet(List<T> list) 
    { 
        // create a set from the List 
        return list.stream().collect(Collectors.toSet()); 
    } 

    public static void main(String args[]) 
    { 

        // Create a stream of integers 
        List<String> list = Arrays.asList("GeeksForGeeks", 
                                          "Geeks", 
                                          "forGeeks", 
                                          "A computer portal", 
                                          "for", 
                                          "Geeks"); 

        // Print the List 
        System.out.println("List: " + list); 

        // Convert List to stream 
        Set<String> set = convertListToSet(list); 

        // Print the Set 
        System.out.println("Set from List: " + set); 
    } 

the example is taken from here. If you need it to be a list you can convert it back with:

List<String> aList = new ArrayList<String>(set); 
  • The OP is asking about a Java array of numbers, not a List of objects. And you can just do `new HashSet<>(list)`. No need to use a Stream. – JB Nizet Nov 24 '19 at 08:45
  • @JBNizet this is one of the example that I found, there are many ways to do it. I added a link that has more options – Dimitris Karagiannis Nov 24 '19 at 08:47
  • 1
    If there are many ways to do it, why not answer with one of them, instead of answering with a way to do something else? – JB Nizet Nov 24 '19 at 08:49
  • @JBNizet there are many ways to convert a List to a Set, the back conversion can be done with 1 line as showed above – Dimitris Karagiannis Nov 24 '19 at 08:51
  • But the array doesn't want to concert a List of objects to a Set. She wants to remove duplicates from an *array* or *numbers*. – JB Nizet Nov 24 '19 at 08:53