如何在Java8中打印唯一的数字平方?
这是我的代码,用于查找唯一的数字并打印其平方。如何将此代码转换为java8,因为流式API会更好如何在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
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"))
);