它是jdk8 的java新特性, 主要是针对集合进行数据的筛选和查找操作,是一种高效且易用的数据处理方式 ,所以可以直接使用stream流来替代for或者while循环的使用。
List<String> strings = Arrays.asList("1", "2", "3");
// 返回一个顺序流
Stream<String> stream = strings.stream();
// 返回一个并行流
Stream<String> stringStream = strings.parallelStream();
可以把上面的集合直接转化为数组
Stream<Object> stream1 = Arrays.stream(strings.toArray());
Stream<Integer> integerStream = Stream.of(1, 2, 3, 5, 6, 7, 8);
Stream<String> stringStream1 = Stream.of("11", "22", "33");
inspectorUpholds.stream()
.map(InspectorUphold::getPerid)
.collect(Collectors.toList()).forEach(System.out::println);
list.stream().sorted(Comparator
.comparingInt(Student::getAge));
// 计算学生总分
List<Student> studentList = StudentData.getStudents();
Stream<Double> doubleStream = studentList.stream().map(Student::getScore);
Optional<Double> reduce1 = doubleStream.reduce(Double::sum);
System.out.println(reduce1.orElse(0.0));
Set<String> set = inspectorUpholds.stream()
.collect(Collectors.groupingBy(InspectorUphold::getPerid))
.keySet();
List<String> collect1 = inspectorUpholds.stream()
.map(InspectorUphold::getPerid)
.collect(Collectors.toList());
inspectorUpholds.stream()
.map(InspectorUphold::getPerid)
.collect(Collectors.toList()).forEach(System.out::println);
list为大的集合,zjlist小的
List<? extends List> list1 = list.stream().filter(item -> zjstringsList.stream().allMatch(each -> !item.equals(each))).collect(Collectors.toList());
## java8新特性(lamda,Stream流)
### lamda
lamda: (parameters)->{expressions};或者()->expressions;
### Stream流
java8出现的一种用于对集合的进行数据操作的工具。
是数据渠道,用于操作集合、数组等,所生成的序列。**流讲的是计算。**
注意:
1. Stream自己不会存储元素
2. 会返回一个新的Stream
3. Stream操作是延迟执行的。
流程:
数据源(转换为流)----》流水线的操作(filter,map,sort,limit,collect)--->变为一个新的流。
1. filter-接收Lamda,从流中排除某些元素
2. limit()-限制元素的个数
3. skip(n)跳过前n个元素,不足n个,则返回一个空流。与limit(n)互补
4. distinct---筛选操作,通过hashCode()和equals()方法去除重复元素
### 创建流
```java
package com.hou.demo.stream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CreateStream {
public static void main(String[] args) {
int[] arrays = new int[10];
IntStream stream = Arrays.stream(arrays);
ArrayList<String> list = new ArrayList<>();
list.stream();
Stream<String> aa = Stream.of("aa", "b", "c", "d", "e");
aa.forEach(System.out::println);
User user = new User();
Stream.of(user);
// 创建无限流
Stream<Integer> iterate = Stream.iterate(0, x -> x + 2).limit(5).skip(3);
iterate.forEach(System.out::println);
}
}
package com.hou.demo.stream;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Optional;
/*
* 终止操作
* */
public class TestStream3 {
User user1 = new User(1, "h", 18, User.Status.FREE);
User user2 = new User(1, "ho", 19, User.Status.BUSY);
User user3 = new User(1, "h", 20,User.Status.BUSY);
User user4 = new User(1, "h", 17,User.Status.VOCATION);
/*
* 查找和匹配
* allMatch--检查是否匹配所有元素
* anyMathch--检查是否至少匹配一个元素
* noneMatch
* FindFirst
* findAny
* count --返回流中元素总个数
* max --返回流中最大值
* min --返回流中最小值
*
*
*
* */
@Test
public void test(){
ArrayList<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
boolean allMatch = list.stream().allMatch(u -> {
return u.getStatus().equals(User.Status.BUSY);
});
System.out.println(allMatch);
boolean b = list.stream()
.anyMatch(u -> {
return u.getStatus().equals(User.Status.BUSY);
});
System.out.println(b);
long count = list.parallelStream().count();
System.out.println(count);
list.stream().allMatch(
u ->{
return u.getStatus().equals(User.Status.BUSY);
}
);
Optional<User> first = list.stream()
.sorted((u1, u2) -> {
return u1.age.compareTo(u2.age);
})
.findFirst();
User user = first.get();
System.out.println(user);
//这样可以有效的避免空指针
Optional<User> userMax = list.stream()
.max((u1, u2) -> Integer.compare(u1.getAge(), u2.getAge()));
System.out.println(userMax.get());
Integer ageMin = list.stream()
.map(User::getAge)
.min(Integer::compare).get();
System.out.println(ageMin);
}
}
package com.hou.demo.forkJoin;
import java.time.Duration;
import java.time.Instant;
import java.util.stream.LongStream;
public class LongStreamRangeClosedDemo {
public static void main(String[] args) {
test3();
// test1();
}
public static void test1() {
Instant start = Instant.now();
Long sum=0L;
for (int i = 0; i < 100000000L; i++) {
sum +=i;
}
System.out.println("sum="+sum);
Instant end = Instant.now();
System.out.println("time="+Duration.between(start,end ).toMillis());
}
public static void test3(){
long start = System.currentTimeMillis();
Instant start1 = Instant.now();
// 并行流 0-1000000000计算总共的和
long sum = LongStream.rangeClosed(0L, 100000000L).parallel().reduce(0, Long::sum);
System.out.println("sum="+sum);
long end = System.currentTimeMillis();
Instant end1 = Instant.now();
Duration between = Duration.between(start1, end1);
System.out.println("between="+between);
System.out.println("time="+Duration.between(start1,end1).toMillis());
}
}
package com.hou.demo.stream;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamFunctionTest {
User user1 = new User(1, "huige", 19, User.Status.BUSY);
User user2 = new User(2, "luhonglan", 19, User.Status.FREE);
User user6 = new User(2, "luhonglan", 52, User.Status.VOCATION);
User user3 = new User(0, "houfang", 20,User.Status.VOCATION);
User user4 = new User(10, "houzhicong", 21);
User user5 = new User(19, "houzhicong", 21);
ArrayList<User> list = new ArrayList<>();
@Test
public void test6() {
User user1 = new User(1, "h", 18);
User user2 = new User(2, "ho", 19);
User user3 = new User(0, "h", 20);
User user4 = new User(10, "h", 21);
ArrayList<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
// sorted自然排序
List list1 = new ArrayList<>();
list1.add(33);
list1.add(11);
list1.add(22);
list1.add(00);
list1.stream().sorted().forEach(System.out::println);
// 定制排序
list.stream()
.sorted((u1,u2)->{
if(u1.username.equals(u2.username)){
return u1.age.compareTo(u2.age);
}else {
return u1.username.compareTo(u2.username);
}
})
.forEach(System.out::println);
// 这个是不执行的 是惰性加载 懒加载
Stream<User> stream = list.stream().filter(user -> {
System.out.println("中间操作");
return user.age > 18;
});
// forEach的时候才执行
// stream.forEach(System.out::println);
// dinstinct 去重操作一定要生成hashCode()和equals方法才可以进行去重
List<User> users = Arrays.asList(new User(9, "hzc", 108), new User(9, "liuke", 108),
new User(9,"kz",108),
new User(19,"kz",108),
new User(29,"kz",109));
users.stream().filter(user -> user.username.contains("k")).distinct().forEach(System.out::println);
}
// map映射,接收Lamda
// flatMap
@Test
public void test1(){
List<String> list = Arrays.asList("aa", "bb", "cc", "dd", "ee");
List list1 = new ArrayList();
list1.add("11");
list1.add("22");
/*
* [11, 22, [aa, bb, cc, dd, ee]]
[11, 22, [aa, bb, cc, dd, ee], aa, bb, cc, dd, ee]
*
* */
list1.add(list);
System.out.println(list1);
list1.addAll(list);
System.out.println(list1);
}
@Test
public void test(){
List<String> list = Arrays.asList("aa", "bb", "cc", "dd", "ee");
// 区别
list.stream()
.map(str ->str.toUpperCase())
.forEach(System.out::println);
/*list.stream()
.map(User::getUsername).forEach(System.out::println);
*/
Stream<Stream<Character>> stream = list.stream()
.map(StreamFunctionTest::filterCharacter);
// flatMap和map的区别会把多个流变为一个流
Stream<Character> characterStream = list.stream().flatMap(StreamFunctionTest::filterCharacter);
}
public static Stream<Character> filterCharacter(String string){
ArrayList<Character> list = new ArrayList<>();
char[] chars = string.toCharArray();
for (Character ch:chars
) {
list.add(ch);
}
return list.stream();
}
/*
* 归约
* reduce(T identity,BinaryOperator) /reduce(BinaryOperator) -可以
* 可以将流中元素反复结合起来,得到一个值。
*
*
* */
@Test
public void test3(){
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);
System.out.println(sum);
// 用户
List<User> users = Arrays.asList(new User(9, "hzc", 108), new User(9, "liuke", 108),
new User(9,"kz",108),
new User(9,"kz",108),
new User(9,"kz",108));
Optional<Integer> sum1 = users.stream()
.map(User::getAge)
.reduce(Integer::sum);
System.out.println(sum1.get());
}
/*
* collectors --将流转换为其他形式。接收一个Collector接口,用于给Stream做汇总的方法。
*
* */
@Test
public void test5() {
list.add(user1);
list.add(user2);
/* list.add(user3);
list.add(user4);*/
Set<String> collect = list.stream()
.map(User::getUsername)
.collect(Collectors.toSet());
System.out.println(collect);
List<String> collect1 = list.stream()
.map(User::getUsername)
.collect(Collectors.toList());
System.out.println(collect1);
HashSet<String> collectHashSet = list.stream()
.map(User::getUsername)
.collect(Collectors.toCollection(HashSet::new));
System.out.println("hashSet打印出来:"+collectHashSet);
collectHashSet.forEach(System.out::println);
Integer minAge = list.stream()
.map(User::getAge)
.collect(Collectors.minBy(Integer::compare)).get();
System.out.println("最小年龄:"+minAge);
Integer maxAge = list.stream()
.map(User::getAge)
.collect(Collectors.maxBy(Integer::compare)).get();
System.out.println("最大年龄:"+maxAge);
// 年龄总和
Integer ageCount = list.stream()
.collect(Collectors.summingInt(User::getAge));
System.out.println(ageCount);
}
/*
* 分组
* */
@Test
public void test7(){
// 一级分组
list.add(user1);
list.add(user2);
list.add(user6);
Map<User.Status, List<User>> map = list.stream()
// User::getStatus 注意一下这个不可以为空会报: java.lang.NullPointerException: element cannot be mapped to a null key
.collect(Collectors.groupingBy(User::getStatus));
System.out.println(map);
// 多级
Map<User.Status, Map<String, List<User>>> map1 = list.stream()
.collect(Collectors.groupingBy(User::getStatus, Collectors.groupingBy(
u -> {
if (u.getAge() <= 35) {
return "青年";
} else if (u.getAge() <= 50) {
return "中年";
} else {
return "老年";
}
}
)));
System.out.println("多级分类map1="+map1);
}
/*
* 分区 符合的返回一个true区,不符合的返回一个false区
*
* */
@Test
public void test8() {
list.add(user1);
list.add(user2);
list.add(user3);
Map<Boolean, List<User>> map = list.stream()
.collect(Collectors.partitioningBy(
u -> u.age > 20
));
System.out.println("分区map(true=[],false=[])"+map);
IntSummaryStatistics iss = list.stream()
.collect(Collectors.summarizingInt(User::getAge));
System.out.println("年龄的平均值"+iss.getAverage());
System.out.println("年龄的总和:"+iss.getSum());
System.out.println("年龄的最大值" + iss.getMax());
/*
* join(",")进行连接
*
* 返回结果
* (huige,luhonglan,houfang)
*
* */
String str = list.stream()
.map(User::getUsername)
.collect(Collectors.joining(",","(",")"));
System.out.println(str);
}
}