How to print only the unique values from array in Java

2 Answers

0 votes
import java.util.Arrays;
 
public class MyClass {
    public static void main(String args[]) {
        Integer arr[] = {5, 2, 1, 3, 7, 1, 5, 9, 3, 3, 3, 2};
  
        Arrays.stream(arr).distinct().forEach((n) -> System.out.printf("%d ", n));
    }
}
  
 
  
  
/*
run:
  
5 2 1 3 7 9 
  
*/

 



answered Sep 22, 2020 by avibootz
edited Aug 20, 2021 by avibootz
0 votes
import java.util.Arrays; 
import java.util.Set; 
import java.util.TreeSet; 

public class MyClass {
    public static void main(String args[]) {
        Integer arr[] = {5, 2, 1, 3, 7, 1, 5, 9, 3, 3, 3, 2, 2};
  
        Set<Integer> uniqValues = new TreeSet<Integer>();
        uniqValues.addAll(Arrays.asList(arr));
         
        System.out.println(uniqValues);
    }
}
  
  
  
  
/*
run:
  
[1, 2, 3, 5, 7, 9]
  
*/

 



answered Aug 20, 2021 by avibootz
edited Dec 7, 2021 by avibootz

Related questions

1 answer 144 views
3 answers 227 views
3 answers 175 views
1 answer 152 views
1 answer 113 views
3 answers 99 views
1 answer 173 views
...