首先我们要有两个对象分别是 学生信息 和 学生住宿信息
class Student {
private Integer studentUserId;
private String name;
}
class studentRooms {
private Integer studentUserId;
private String roomInfo;
}
将对象填充参数
List<Student> students = new ArrayList<>();
students.add(Student.builder().studentUserId(111).name("张三").build());
students.add(Student.builder().studentUserId(222).name("李四").build());
List<StudentRoom> studentRooms = new ArrayList<>();
studentRooms.add(StudentRoom.builder().studentUserId(222).roomInfo("住宿").build());
studentRooms.add(StudentRoom.builder().studentUserId(111).roomInfo("走读").build());
这时我们的需求是, 将两边集合数据中, 相同studentUserId 数据拼接到一起返回给前端 如:
{
"studentUserId":111,
"name":"张三",
"roomInfo":"走读"
}
这时候我们常规的写法就是 遍历两个集合 判断studentUserId 如果相同则拼装数据
for (Student student : students) {
for (StudentRoom studentRoom : studentRooms) {
if (student.getStudentUserId().equals(studentRoom.getStudentUserId())) {
System.out.println("拼装数据返回给前端");
}
}
}
上述这种写法面临最大的问题就是时间复杂度为O(n^2)对 n 个数进行排序,需要扫描 n X n 次
对于上述代码也就是 2 x 2 = 4次
那么如何优化这种情况呢? 这里我们可以采用JDK1.8新特性的 stream流做处理代码如下
Map<Integer, StudentRoom> studentRoomByUserId = studentRooms.stream().collect(Collectors.toMap(StudentRoom::getStudentUserId, Function.identity()));
for (Student student : students) {
StudentRoom studentRoom = studentRoomByUserId.get(student.getStudentUserId());
if (studentRoom != null) {
System.out.println("拼装数据返回给前端");
}
}
按照上述这种操作方法会大大减少时间复杂度为O(n), 而循环的次数也变为了2次
完整代码
public class Test{
@Data
@Builder
class Student {
private Integer studentUserId;
private String name;
}
@Data
@Builder
class StudentRoom {
private Integer studentUserId;
private String roomInfo;
}
public void test() {
List<Student> students = new ArrayList<>();
students.add(Student.builder().studentUserId(111).name("张三").build());
students.add(Student.builder().studentUserId(222).name("李四").build());
List<StudentRoom> studentRooms = new ArrayList<>();
studentRooms.add(StudentRoom.builder().studentUserId(222).roomInfo("住宿").build());
studentRooms.add(StudentRoom.builder().studentUserId(111).roomInfo("走读").build());
Map<Integer, StudentRoom> studentRoomByUserId = studentRooms.stream().collect(Collectors.toMap(StudentRoom::getStudentUserId, Function.identity()));
for (Student student : students) {
StudentRoom studentRoom = studentRoomByUserId.get(student.getStudentUserId());
if (studentRoom != null) {
System.out.println("拼装数据返回给前端");
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)