/**
* 求勾股数 a*a + b*b =c*c
*/
List<double[]> sanYuanSun = IntStream.rangeClosed(1, 100).boxed().flatMap(a -> IntStream.rangeClosed(a, 100).mapToObj(b -> new double[]{a, b, Math.sqrt(a * a + b * b)})
.filter(c -> c[2] % 1 == 0)).collect(Collectors.toList());
sanYuanSun.forEach(e -> {
System.out.println(e[0] + "," + e[1] + "," + e[2]);
});
long wordCount = 0;
try(Stream<String> lines = Files.lines(Paths.get("D:\\desktop\\lol.txt"), Charset.defaultCharset())) {
wordCount = lines.flatMap(a -> Arrays.stream(a.split(""))).distinct().count();
System.out.println(wordCount);
}catch(Exception e) {
}
/**
*斐波纳契数列是著名的经典编程练习。下面这个数列就是斐波纳契数列的一部分:0, 1, 1,
* 2, 3, 5, 8, 13, 21, 34, 55…数列中开始的两个数字是0和1,后续的每个数字都是前两个数字之和。
* 斐波纳契元组序列与此类似,是数列中数字和其后续数字组成的元组构成的序列:(0, 1),
* (1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13), (13, 21) …
*/
Stream.iterate(new int[]{0 ,1}, n -> new int[]{n[1], n[0] + n[1]}).limit(20).forEach(e -> {
System.out.println("[" + e[0] + "," + e[1] + "]");
});
/**
* 这段代码将生成一个流,其中有五个0到1之间的随机双精度数
*/
Stream.generate(Math::random).limit(5).forEach(e -> {
System.out.println(e);
});
List<Picture> pictures = new ArrayList<>();
String[] urls = {"once", "twice", "thread"};
for (int i = 0; i < 5; i++) {
Picture picture = new Picture();
picture.setSize((long) i);
if( i > 2) {
picture.setType((byte) 2);
} else {
picture.setType((byte)1);
}
picture.setName("cesi: " + i);
picture.setUrl(urls[new Random().nextInt(3)]);
pictures.add(picture);
}
//求最大值
Optional<Picture> maxPic = pictures.stream().collect(Collectors.maxBy(Comparator.comparingLong(Picture::getSize)));
System.out.println(maxPic.orElse(new Picture()));
//求最小值
Optional<Picture> minPic = pictures.stream().collect(Collectors.minBy(Comparator.comparingLong(Picture::getSize)));
System.out.println(minPic.orElse
Java8学习笔记
最新推荐文章于 2022-03-30 17:19:20 发布