2

Here is my code to find the unique number and print the squares of it. How can I convert this code to java8 as it will be better to stream API?

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
HashSet<Integer> uniqueValues = new HashSet<>(numbers);

for (Integer value : uniqueValues) {
    System.out.println(value + "\t" + (int)Math.pow(value, 2));
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
NullPointer
  • 7,094
  • 5
  • 27
  • 41

3 Answers3

3

Use IntStream.of with distinct and forEach:

IntStream.of(3, 2, 2, 3, 7, 3, 5)
         .distinct()
         .forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));

or if you want the source to remain as a List<Integer> then you can do as follows:

numbers.stream()
       .distinct()
       .forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));

yet another variant:

new HashSet<>(numbers).forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 1
    I want to go with 2nd one.thanks for the answer again – NullPointer Jul 20 '18 at 17:45
  • sorry one question.In 2nd and 3rd which one will be efficient ? – NullPointer Jul 20 '18 at 17:47
  • 1
    @NullPointer I'd say the 3rd variant would be more efficient than the 2nd as it doesn't have the stream overhead. – Ousmane D. Jul 20 '18 at 17:49
  • 2
    Don’t be surprised if `System.out.println` turns out to be the most expensive operation and thus, `System.out.println( numbers.stream() .distinct() .map(n -> n+"\t"+n*n) .collect(Collectors.joining("\n")) );` is even faster. However, only a benchmark can tell. – Holger Jul 20 '18 at 19:46
1
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream()
    .distinct()
    .map(n -> String.join("\t",n.toString(),String.valueOf(Math.pow(n, 2))))
    .forEach(System.out::println);
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
0

As @Holger comments, in above answers System.out.println looks most expensive operation.

May be we can do it in more faster way like:

 List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
 System.out.println( numbers.stream()
                     .distinct()
                     .map(n -> n+"\t"+n*n) 
                     .collect(Collectors.joining("\n")) 
                   );
NullPointer
  • 7,094
  • 5
  • 27
  • 41