package hk.org.ha.tims;
import hk.org.ha.tims.dto.vo.UserRoleVo;
import lombok.Data;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamTest {
public static void main(String[] args) {
List<TestVO> demoList = Arrays.asList(new TestVO("1","张三"),new TestVO("2","李四"),new TestVO("3","王五"),new TestVO("4","王五"));
List<TestVO> demoList1 = Arrays.asList(new TestVO("1","张三"),new TestVO("2","李四"),new TestVO("3","王五"),new TestVO("4","王五"));
// for 循环
demoList.stream().forEach(item->{
System.out.println(item.toString());
});
demoList.forEach(item->{
System.out.println(item.toString());
});
// 获取某个字段的list
List<String> names = demoList.stream().map(TestVO::getName).collect(Collectors.toList());
//集合转map
Map<String,String> idNameMap = demoList.stream().collect(Collectors.toMap(TestVO::getId, TestVO::getName));
Map<String,TestVO> idVOMap = demoList.stream().collect(Collectors.toMap(TestVO::getId, Function.identity()));
//key重复处理
Map<String,TestVO> duplicateKeyMap = demoList.stream().collect(Collectors.toMap(TestVO::getId, Function.identity(),(item1,item2)->item2));
//分组
Map<String,List<TestVO>> idGroupMap =demoList.stream().collect(Collectors.groupingBy(TestVO::getId,Collectors.toList()));
//过滤
List<TestVO> filterResult = demoList.stream().filter(item->"李四".equals(item.getName())).collect(Collectors.toList());
//根据某个字段去重
List<TestVO> distinctResult = demoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TestVO::getName))), ArrayList::new));
//limit 取前N条
demoList.stream().limit(2).collect(Collectors.toList());
//skip 跳过前N条
demoList.stream().skip(2).collect(Collectors.toList());
//排序
demoList.stream().sorted(new Comparator<TestVO>() {
@Override
public int compare(TestVO o1, TestVO o2) {
return o1.getId().compareTo(o2.getId());
}
});
// 合并
List<TestVO> resultList = Stream.concat(demoList.stream(),demoList1.stream()).collect(Collectors.toList());
//parallelStream
demoList.parallelStream().forEach(item->{
System.out.println(item.toString());
});
}
}
@Data
class TestVO{
private String id;
private String name;
public TestVO(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "TestVO{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}