设计一个测试类Tuser
package org.example;
import com.alibaba.fastjson.annotation.JSONField;
import java.io.Serializable;
public class Tuser implements Serializable {
//用户名
private String name;
//平台名称
private String sys;
//登录次数
private int times;
//一个合并属性的key
@JSONField(serialize =false)
private String key;
public String getKey(){
return name+sys;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSys() {
return sys;
}
public void setSys(String sys) {
this.sys = sys;
}
public int getTimes() {
return times;
}
public void setTimes(int times) {
this.times = times;
}
}
编写Main测试类
package org.example;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest {
public static void main(String[] args) {
Tuser t1 = new Tuser();
t1.setName("tom");
t1.setSys("web");
t1.setTimes(5);
Tuser t2 = new Tuser();
t2.setName("jack");
t2.setSys("web");
t2.setTimes(10);
Tuser t3 = new Tuser();
t3.setName("lili");
t3.setSys("app");
t3.setTimes(12);
Tuser t4 = new Tuser();
t4.setName("lili");
t4.setSys("app");
t4.setTimes(9);
Tuser t5 = new Tuser();
t5.setName("tom");
t5.setSys("web");
t5.setTimes(10);
List<Tuser> tuserList = new ArrayList<>();
tuserList.add(t1);
tuserList.add(t2);
tuserList.add(t3);
tuserList.add(t4);
tuserList.add(t5);
//取出名字并去重
List<String> userNames = tuserList.stream().map(tuser -> tuser.getName()).distinct().collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(userNames));
//找出登陆次数大于5次的数据
List<Tuser> users = tuserList.stream().filter(tuser -> tuser.getTimes() > 5
).collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(users));
//找出同一个人登录统一平台的总次数输出新列表
List<Tuser> tusers = tuserList.stream()
.collect(Collectors.toMap(Tuser::getKey, a -> a, (o1, o2) -> {
o1.setTimes(o1.getTimes() + o2.getTimes());
return o1;
})).values().stream().collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(tusers));
}
}
输出结果:
//取出名字并去重
["tom","jack","lili"]
//找出登陆次数大于5次的数据
[{"name":"jack","sys":"web","times":10},{"name":"lili","sys":"app","times":12},{"name":"lili","sys":"app","times":9},{"name":"tom","sys":"web","times":10}]
//找出同一个人登录统一平台的总次数输出新列表
[{"name":"tom","sys":"web","times":15},{"name":"jack","sys":"web","times":10},{"name":"lili","sys":"app","times":21}]
参考文章:
Java8中Stream详细用法大全_stream用法_大梦谁先觉i的博客-CSDN博客