import com.google.common.collect.Lists;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Student student = new Student("张三", "北京");
Student student2 = new Student("李四", "北京");
Student student3 = new Student("王五", "郑州");
Student student4 = new Student("赵六", "北京");
ArrayList<Student> list = Lists.newArrayList();
list.add(student);
list.add(student2);
list.add(student3);
list.add(student4);
//1.统计department属性相同的个数
Map<String, Long> countByDepartment = list.stream()
.collect(Collectors.groupingBy(Student::getCity, Collectors.counting()));
//2.筛选统计结果大于1个的数据
Map<String, Long> statisticsData = countByDepartment.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
//3.返回需要的数据
List<Student> result = list.stream().filter(param -> statisticsData.keySet().contains(param.getCity()))
.collect(Collectors.toList());
System.out.println(result);
}
}
@Data
class Student{
private String name;
private String city;
public Student(String name,String city){
this.name = name;
this.city = city;
}
}
java8流式编程统计属性相同个数大于1的数据
于 2023-01-09 10:35:39 首次发布
该代码示例展示了一个Java程序,它创建了一个Student对象的列表,然后使用StreamAPI和Collectors对列表进行操作。首先,通过groupingBy方法按学生所在城市进行分组并计算每个城市的数量。接着,筛选出城市数量大于1的学生,最后返回包含这些城市的所有学生列表。
摘要由CSDN通过智能技术生成