1

I am trying to remove duplicate values by converting an array to an arraylist and then further converting the arraylist to a Hashset. As we know hashsets do not contain any duplicate values. But i am not getting any output. I am implementing this technique because I want to avoid using a for loop .

import java.util.*;

public class RemoveDupliucate {

public static void main(String[] args) {
    int a[]= {1,2,1,3,2,15,4,6,4};

    List l=Arrays.asList();

    TreeSet<Integer> m=new TreeSet(l);
    for(Integer i:m)
    {
        System.out.print(i);
    }



}

i am not getting any output.

Shreyash Sharma
  • 180
  • 2
  • 14
Ajay kumar
  • 29
  • 3
  • 1
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – Andy Turner Aug 06 '19 at 07:17
  • 2
    You don't do anything with `a`. You are constructing an empty list, copying it into a `TreeSet`, and then looping over the `TreeSet`, which is, of course, empty, so the loop body is never executed. (And `Arrays.asList(a)` isn't what you want to use, either). – Andy Turner Aug 06 '19 at 07:18
  • 1
    Please avoid naming variable with a single character, especially “l”. Some font will display ‘l’ and “1” nearly the same – tiboo Aug 06 '19 at 08:20

3 Answers3

2

If you want to remove duplicate elements from an array, there is already a method using java 8 stream,

Arrays.stream('array').distinct().toArray();

Which will remove all the duplicate elements and return the array.

for your code,

int a[]= {1,2,1,3,2,15,4,6,4};

a = Arrays.stream(a).distinct().toArray();

this should work, if you want to remove duplicates.

JavaLearner1
  • 607
  • 2
  • 8
  • 21
1

This line will create an empty list, that’s why you got no output:

List l = Arrays.asList();

It should be something like

List<Integer> l = Arrays.asList(1,2,1,3,2,15,4,6,4);

lolacoco
  • 101
  • 8
tiboo
  • 8,213
  • 6
  • 33
  • 43
0

It is very easy in Java 8 streams

int array[]= {1,2,1,3,2,15,4,6,4};

//Use Java 8 Streams to get distinct values from an array 
int[] unique = Arrays.stream(array).distinct().toArray();

If you don't want to use Java 8 streams API you can try in below Converting array into set

public void printDistinctElements(int[] inputArray)
{
    Set<Integer> elementSet = new HashSet<Integer>();

    for(int i = 0; i<inputArray.length; i++)
    {
        elementSet.add(inputArray[i]);
    }

    System.out.println("Distinct Elements");
    for (int i : elementSet) {
        System.out.print(" " +i);
    }
}
Dinesh K
  • 269
  • 2
  • 8