Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java8中打印唯一的数字平方?_Java_List_Java 8_Unique_Perfect Square - Fatal编程技术网

如何在Java8中打印唯一的数字平方?

如何在Java8中打印唯一的数字平方?,java,list,java-8,unique,perfect-square,Java,List,Java 8,Unique,Perfect Square,这是我的代码,用于查找唯一的数字并打印其平方。如何将此代码转换为java8,因为流式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

这是我的代码,用于查找唯一的数字并打印其平方。如何将此代码转换为java8,因为流式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));
}
List number=Arrays.asList(3,2,2,3,7,3,5);
HashSet uniqueValues=新的HashSet(数字);
for(整数值:唯一值){
System.out.println(value+“\t”+(int)Math.pow(value,2));
}

IntStream.of
distinct
forEach
一起使用:

IntStream.of(3, 2, 2, 3, 7, 3, 5)
         .distinct()
         .forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));
或者,如果希望源代码保持为
列表
,则可以执行以下操作:

numbers.stream()
       .distinct()
       .forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));
另一种变体:

new HashSet<>(numbers).forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));
newhashset(numbers).forEach(n->System.out.println(n+“\t”+(int)Math.pow(n,2));
列表编号=数组。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);

如@Holger评论所示,在上述答案中,System.out.println看起来是最昂贵的操作

也许我们可以用更快捷的方式,比如:

 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")) 
                   );
List number=Arrays.asList(3,2,2,3,7,3,5);
System.out.println(numbers.stream()
.distinct()
.map(n->n+“\t”+n*n)
.collect(收集器.连接(“\n”))
);

我想用第二个。再次感谢你的回答。还有一个问题。在第二个和第三个版本中,哪一个会更有效?@NullPointer我想说第三个版本会比第二个版本更有效,因为它没有流开销。如果
System.out.println
被证明是最昂贵的操作,请不要惊讶,
System.out.println(numbers.stream().distinct().map(n->n+“\t”+n*n).collect(collector.joining(“\n”))甚至更快。然而,只有一个基准可以判断。
 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")) 
                   );