stream测试
/**
* @Author: liuxuewei
* @Date: 2022/6/28 19:22
* @Description:
*/
public class Test20220628 {
public static void main(String[] args) {
List<Demo> list = new ArrayList<>();
list.add(new Demo(1,"lxw"));
list.add(new Demo(2,"ydd"));
list.add(new Demo(3,"lyy"));
list.add(new Demo(3,"test"));
System.out.println("list=>" + list);
//list=>[Test20220628.Demo(pid=1, name=lxw), Test20220628.Demo(pid=2, name=ydd), Test20220628.Demo(pid=3, name=lyy), Test20220628.Demo(pid=3, name=test)]
//现在有个需求,需要把list中的所有pid取出来,单独形成一个list列表
//原先做法
List<Integer> pids1 = new ArrayList<>();
for (Demo demo : list) {
pids1.add(demo.getPid());
}
System.out.println(pids1);
//使用stream做法
List<Integer> pids2 = list.stream().map(r -> r.getPid()).distinct().collect(Collectors.toList()); //取出对象列表中的某数据并去重得到列表
System.out.println("pids2=>" + pids2);
//pids=>[1, 2, 3]
list.stream().collect(Collectors.groupingBy(r -> r.getPid())).forEach((k,v)->{
System.out.println("K=>" + k + ";v=>" + v);//k代表group的k值,这里就是pid,v代表k对应的对象列表[所以这里取值要用v.get(0)],这里就是一个具体的Demo对象
System.out.println(v.get(0));
});
for (Demo demo : list) {
System.out.println(demo);
}
}
@Data
@AllArgsConstructor
public static class Demo{
Integer pid;
String name;
}
}
评论区