前言
今天学习代码的时候,看到了有关流的使用,于是在网上找个几篇有关于流的技术文章,运行一番,做个记录
**
1,什么是斐波那契数列?
**
每一个数为前面两个数之和
如 1,1,2,3,5,8,13,21,34,55
**
2,实现代码
**
代码一:
public static void main(String[] args) {
// a,b,c
int a = 1;
int b = 1;
int c = 0;
System.out.print(a + "\t" + b + "\t");
for (int i = 3; i <= 10; i++) {
// 每次运算之后,将数值向后移位
c = a + b;
a = b;
b = c;
System.out.print(c + "\t");
}
}
代码二:
public static void main(String[] args) {
int[] arr = new int[10];
arr[0] = 1;
arr[1] = 1;
for(int i = 0;i < arr.length;i++) {
if(i > 1) {
arr[i] = arr[i - 2] + arr[i - 1];
}
System.out.print(arr[i] + "\t");
}
}
代码三:(递归写法)
public class PrintFib {
public static int fib(int num) {
if(num == 1 || num == 2) {
return 1;
}else {
return fib(num - 2) + fib(num - 1);
}
}
//主函数(程序入口)
public static void main(String[] args) {
for(int i = 1;i <= 10;i++) {
System.out.print(fib(i) + "\t");
}
}
}
代码四:(流操作)
public static void main(String[] args) {
Stream.iterate(new int[]{0, 1}, n -> new int[]{n[1], n[0] + n[1]})
.limit(10)
.map(n -> n[1])
.forEach(x -> System.out.print(x+ ","));
}
3,知识引申
Java 8 stream用法
1,创建流
集合创建
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream(); //获取一个顺序流
Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
数组创建
Integer[] arrs = new Integer[]{1,2,3,4,5,6};
Stream<Integer> stream = Arrays.stream(arrs);
stream = Stream.of(1,2,3,4,5,6);
of() 方法内部其实调用了 Arrays.stream() 方法。
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 2).limit(6);
stream2.forEach(System.out::print); // 0 2 4 6 8 10
Stream<Double> stream3 = Stream.generate(Math::random).limit(2);
stream3.forEach(System.out::print); //生成两个随机数
将文件的每行内容转为流
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("F:\\test_stream.txt"));
Stream<String> lineStream = reader.lines();
lineStream.forEach(System.out::println);
}catch (Exception e){
}
}
将字符串分隔成流
public static void main(String[] args) {
Pattern pattern = Pattern.compile(",");
Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");
stringStream.forEach(System.out::print);//abcd
}
2、操作流
筛选与切片
filter:过滤流中的某些元素
limit(n):获取n个元素
skip(n):跳过n元素,配合limit(n)可实现分页
distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 3, 5, 7, 8, 8, 9, 10);
Stream<Integer> newStream = stream.filter(s -> s > 5) //7 8 8 9 10
.distinct() //7 8 9 10
.skip(2) //9 10
.limit(2); //9 10
newStream.forEach(System.out::println);
}
类名 :: 方法名是 Java 8 引入的新语法,System.out 返回 PrintStream 类,println 方法打印
映射
map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
public static void main(String[] args) {
List<String> list = Arrays.asList("a,b,c", "1,2,3");
Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", ""));
s1.forEach(System.out::println); // abc 123
Stream<String> s3 = list.stream().flatMap(s -> {
Stream<String> s2 = Arrays.stream(s.split(","));
return s2;
});
s3.forEach(System.out::println); // a b c 1 2 3
}
// 把 Stream<String> 的流转成一个 Stream<Integer> 的流。
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("0");
list.add("00");
list.add("000");
Stream<Integer> stream = list.stream().map(String::length);
stream.forEach(System.out::println);// 1 2 3
}
// peek:如同于map,能得到流中的每一个元素。
// 但map接收的是一个Function表达式,有返回值;
// 而peek接收的是Consumer表达式,没有返回值。
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
studentList.stream()
.peek(o -> o.setAge(100))
.forEach(System.out::println);
//结果:
Student{name='aa', age=100}
Student{name='bb', age=100}
排序
public static void main(String[] args) {
List<String> list = Arrays.asList("aa", "ff", "dd");
list.stream().sorted().forEach(System.out::println);// aa dd ff
Student s1 = new Student("a", 1);
Student s2 = new Student("b", 2);
Student s3 = new Student("c", 3);
List<Student> studentList = Arrays.asList(s1, s2, s3);
//先按姓名升序,姓名相同则按年龄升序
studentList.stream().sorted(
(o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return o1.getAge() - o2.getAge();
} else {
return o1.getName().compareTo(o2.getName());
}
}
).forEach(System.out::println);
}
匹配
anyMatch:有一个匹配就true
allMatch:所有都匹配就true
noneMatch:一个都不匹配就true
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("11");
list.add("12");
list.add("13");
boolean anyMatchFlag = list.stream().anyMatch(element -> element.contains("2"));
boolean allMatchFlag = list.stream().allMatch(element -> element.length() > 1);
boolean noneMatchFlag = list.stream().noneMatch(element -> element.endsWith("0"));
System.out.println(anyMatchFlag);//true
System.out.println(allMatchFlag);//true
System.out.println(noneMatchFlag);//true
}
元素组合
public static void main(String[] args) {
Integer[] ints = {0, 1, 2, 3};
List<Integer> list = Arrays.asList(ints);
// 无初始值,数组求和
Optional<Integer> a1 = list.stream().reduce((a, b) -> a + b);
Optional<Integer> b1 = list.stream().reduce(Integer::sum);
System.out.println(a1.orElse(0));//6
System.out.println(b1.orElse(0));//6
//有初始值,初始值相加
int a11 = list.stream().reduce(6, (a, b) -> a + b);
System.out.println(a11);//12
int b11 = list.stream().reduce(6, Integer::sum);
System.out.println(b11);//12
}
3,流转换
流转数组
String[] strArray = list.stream().toArray(String[]::new);
流转集合
List<Integer> list1 = list.stream().map(String::length).collect(Collectors.toList());
List<String> list2 = list.stream().collect(Collectors.toCollection(ArrayList::new));
4,引用链接
使用Java打印斐波那契数列的三种方法
Java 8 stream的详细用法
一文带你入门Java Stream流,太强了