java7从List中取出指定字段等于指定值的对象
时间: 2024-01-21 08:19:00 浏览: 88
假设你有一个 `List`,其中包含一组 Java 对象,每个对象都具有一些属性。你可以使用 Java 7 中的增强 for 循环和条件语句来查找其中属性等于指定值的对象。以下是一个示例代码:
```java
public class MyClass {
private int id;
private String name;
private int age;
public MyClass(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getters and setters
@Override
public String toString() {
return "MyClass{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<MyClass> myList = new ArrayList<MyClass>();
myList.add(new MyClass(1, "Alice", 20));
myList.add(new MyClass(2, "Bob", 25));
myList.add(new MyClass(3, "Charlie", 30));
// find objects where age equals 25
int searchAge = 25;
List<MyClass> resultList = new ArrayList<MyClass>();
for (MyClass obj : myList) {
if (obj.getAge() == searchAge) {
resultList.add(obj);
}
}
// print result
for (MyClass obj : resultList) {
System.out.println(obj);
}
}
}
```
此代码将输出:
```
MyClass{id=2, name='Bob', age=25}
```
阅读全文