问题描述
我认为它很简单,但是我需要一种简单的方法来解决它.
I think it quite simple but I need one ways to solve it easy.
我的问题是:我有列表对象Student包含100个对象
My problem is: I have list object Student include 100 objects
public class Student {
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
现在,我只想让一些年龄为"ABC","BCD","DEF"的学生
Now, I only want to get age of some student has name "ABC", "BCD", "DEF"
所以我会这样做:
Map<String, String> data = new HashMap<>();
List<String> listSpecification = new ArrayList<>(Arrays.asList("ABC", "BCD", "DEF"));
for (Student stu : list<Student>) {
for (int i = 0; i < listSpecification.size(); i++) {
if (stu.getName().equalsIgnoreCase(listSpecification.get(i))) {
data.put(pro.getName(), pro.getValue());
}
}
}
但是,如果我这样做,我认为它对性能不好.那么任何人都可以帮助我另一个案例吗?
But if I do it, I think it not good about performance. So anyone can help me another case ?
推荐答案
您的算法的复杂度为O(m * n),其中m是学生数,n是名称数.使用流API或Collection.contains
的建议不会改变这一点.
Your algorithm has complexity O(m*n) where m is the number of students and n is the number of names. The suggestions to use streaming APIs or Collection.contains
won't change that.
您可以使用从学生姓名到Student
的映射,将其转换为O(m + n)算法:
You can convert this to an O(m + n) algorithm by using a map from student name to Student
:
Map<String, Student> studentsByName = new HashMap<>();
for (Student s : studentList) {
studentsByName.put(s.getName().toLowerCase(), s);
}
这是O(m)运算.然后,您可以遍历规范列表中的所有名称,将每个名称转换为小写,然后直接拔出每个学生.这是一个O(n)操作.还有一个更高的效率,那就是,如果您需要为同一个学生列表处理多个规范列表,则只需要执行一次第一步即可.
That's an O(m) operation. Then you can iterate through all the names in the specification list, convert each to lower case, and pull out each student directly. This is an O(n) operation. There's a further efficiency in that you need do the first step only once if you need to process multiple specification lists for the same student list.
这篇关于从List< Object>获取一些值爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!