这是我的代码,用于查找唯一数字并打印它的平方。我怎样才能将此代码转换为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));
}
最佳答案
使用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)));
或者如果您希望源保留为 List<Integer>
那么你可以执行以下操作:
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)));
关于java - 如何在 Java 8 中打印唯一的数字平方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51447664/