用Stream操作集合,帮你节省至少一半时间

目录

  • Stream简介
  • 为什么要使用Stream
  • 实例数据源
  • Filter
  • Map
  • FlatMap
  • Reduce
  • Collect
  • Optional
  • 并发
  • 调试

Stream简介

  • Java 8引入了全新的Stream API。这里的Stream和I/O流不同,它更像具有Iterable的集合类,但行为和集合类又有所不同。
  • stream是对集合对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作。
  • 只要给出需要对其包含的元素执行什么操作,比如 “过滤掉长度大于 10 的字符串”、“获取每个字符串的首字母”等,Stream 会隐式地在内部进行遍历,做出相应的数据转换。

为什么要使用Stream

  • 函数式编程带来的好处尤为明显。这种代码更多地表达了业务逻辑的意图,而不是它的实现机制。易读的代码也易于维护、更可靠、更不容易出错。
  • 高端

实例数据源

public class Data {
private static List<personmodel> list = null;

static {
PersonModel wu = new PersonModel("wu qi", 18, "男");

PersonModel zhang = new PersonModel("zhang san", 19, "男");

PersonModel wang = new PersonModel("wang si", 20, "女");

PersonModel zhao = new PersonModel("zhao wu", 20, "男");

PersonModel chen = new PersonModel("chen liu", 21, "男");

list = Arrays.asList(wu, zhang, wang, zhao, chen);
}

public static List<personmodel> getData() {
return list;
}

}
/<personmodel>/<personmodel>

Filter

  • 遍历数据并检查其中的元素时使用。
  • filter接受一个函数作为参数,该函数用Lambda表达式表示。
用Stream操作集合,帮你节省至少一半时间

image.png

 /**
* 过滤所有的男性
*/
public static void fiterSex(){

List<personmodel> data = Data.getData();

//old
List<personmodel> temp=new ArrayList<>();
for (PersonModel person:data) {
if ("男".equals(person.getSex())){
temp.add(person);
}
}
System.out.println(temp);

//new
List<personmodel> collect = data
.stream()
.filter(person -> "男".equals(person.getSex()))
.collect(toList());
System.out.println(collect);

}
/**
* 过滤所有的男性 并且小于20岁
*/
public static void fiterSexAndAge(){
List<personmodel> data = Data.getData();

//old
List<personmodel> temp=new ArrayList<>();
for (PersonModel person:data) {
if ("男".equals(person.getSex())&&person.getAge()<20){
temp.add(person);
}
}

//new 1
List<personmodel> collect = data
.stream()
.filter(person -> {
if ("男".equals(person.getSex())&&person.getAge()<20){
return true;

}
return false;
})
.collect(toList());

//new 2
List<personmodel> collect1 = data
.stream()
.filter(person -> ("男".equals(person.getSex())&&person.getAge()<20))
.collect(toList());

}
/<personmodel>/<personmodel>/<personmodel>/<personmodel>/<personmodel>/<personmodel>/<personmodel>

Map

  • map生成的是个一对一映射,for的作用
  • 比较常用
  • 而且很简单
用Stream操作集合,帮你节省至少一半时间

image.png

 /**
* 取出所有的用户名字
*/
public static void getUserNameList(){
List<personmodel> data = Data.getData();

//old
List<string> list=new ArrayList<>();
for (PersonModel persion:data) {
list.add(persion.getName());
}
System.out.println(list);

//new 1
List<string> collect = data.stream().map(person -> person.getName()).collect(toList());
System.out.println(collect);

//new 2
List<string> collect1 = data.stream().map(PersonModel::getName).collect(toList());
System.out.println(collect1);

//new 3
List<string> collect2 = data.stream().map(person -> {
System.out.println(person.getName());
return person.getName();
}).collect(toList());

}
/<string>/<string>/<string>/<string>/<personmodel>

FlatMap

  • 顾名思义,跟map差不多,更深层次的操作
  • 但还是有区别的
  • map和flat返回值不同
  • Map 每个输入元素,都按照规则转换成为另外一个元素。
  • 还有一些场景,是一对多映射关系的,这时需要 flatMap。
  • Map一对一
  • Flatmap一对多
  • map和flatMap的方法声明是不一样的
  • Stream map(Function mapper);
  • Stream flatMap(Function> mapper);
  • map和flatMap的区别:我个人认为,flatMap的可以处理更深层次的数据,入参为多个list,结果可以返回为一个list,而map是一对一的,入参是多个list,结果返回必须是多个list。通俗的说,如果入参都是对象,那么flatMap可以操作对象里面的对象,而map只能操作第一层。
用Stream操作集合,帮你节省至少一半时间

image.png

public static void flatMapString() {

List<personmodel> data = Data.getData();

//返回类型不一样
List<string> collect = data.stream()
.flatMap(person -> Arrays.stream(person.getName().split(" "))).collect(toList());
List<stream>> collect1 = data.stream()
.map(person -> Arrays.stream(person.getName().split(" "))).collect(toList());

//用map实现
List<string> collect2 = data.stream()
.map(person -> person.getName().split(" "))
.flatMap(Arrays::stream).collect(toList());

//另一种方式
List<string> collect3 = data.stream()
.map(person -> person.getName().split(" "))
.flatMap(str -> Arrays.asList(str).stream()).collect(toList());
}
/<string>/<string>/<stream>/<string>/<personmodel>

Reduce

  • 感觉类似递归
  • 数字(字符串)累加
  • 个人没咋用过
用Stream操作集合,帮你节省至少一半时间

image.png

 public static void reduceTest(){

//累加,初始化值是 10
Integer reduce = Stream.of(1, 2, 3, 4)
.reduce(10, (count, item) ->{
System.out.println("count:"+count);
System.out.println("item:"+item);
return count + item;
} );
System.out.println(reduce);

Integer reduce1 = Stream.of(1, 2, 3, 4)
.reduce(0, (x, y) -> x + y);
System.out.println(reduce1);

String reduce2 = Stream.of("1", "2", "3")
.reduce("0", (x, y) -> (x + "," + y));
System.out.println(reduce2);


}

Collect

  • collect在流中生成列表,map,等常用的数据结构
  • toList()
  • toSet()
  • toMap()
  • 自定义
 /**
* toList
*/
public static void toListTest(){
List<personmodel> data = Data.getData();
List<string> collect = data.stream()
.map(PersonModel::getName)

.collect(Collectors.toList());
}

/**
* toSet
*/
public static void toSetTest(){
List<personmodel> data = Data.getData();
Set<string> collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toSet());
}

/**
* toMap
*/
public static void toMapTest(){
List<personmodel> data = Data.getData();
Map<string> collect = data.stream()
.collect(
Collectors.toMap(PersonModel::getName, PersonModel::getAge)
);
data.stream()
.collect(Collectors.toMap(per->per.getName(), value->{
return value+"1";
}));
}

/**
* 指定类型
*/
public static void toTreeSetTest(){
List<personmodel> data = Data.getData();
TreeSet<personmodel> collect = data.stream()
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(collect);
}

/**
* 分组
*/
public static void toGroupTest(){
List<personmodel> data = Data.getData();
Map<boolean>> collect = data.stream()
.collect(Collectors.groupingBy(per -> "男".equals(per.getSex())));
System.out.println(collect);
}

/**
* 分隔

*/
public static void toJoiningTest(){
List<personmodel> data = Data.getData();
String collect = data.stream()
.map(personModel -> personModel.getName())
.collect(Collectors.joining(",", "{", "}"));
System.out.println(collect);
}

/**
* 自定义
*/
public static void reduce(){
List<string> collect = Stream.of("1", "2", "3").collect(
Collectors.reducing(new ArrayList<string>(), x -> Arrays.asList(x), (y, z) -> {
y.addAll(z);
return y;
}));
System.out.println(collect);
}
/<string>/<string>/<personmodel>/<boolean>/<personmodel>/<personmodel>/<personmodel>/<string>/<personmodel>/<string>/<personmodel>/<string>/<personmodel>


作者:我是你的小眼睛儿
链接:https://www.jianshu.com/p/9fe8632d0bc2


分享到:


相關文章: