如何在包含名称和年龄的对象的文件中按名称查找?我想从文件中按名称搜索它。我完成了将对象写入文件并从文件中读取的操作。Demo object1 = new Demo(100,"saran");Demo object2 = new Demo(20 ,"nivas");ArrayList<Demo> list=new ArrayList<>();try { FileOutputStream file=new FileOutputStream("C:\\Users\\SARANNIVAS\\Documents\\file\\obj"); ObjectOutputStream out=new ObjectOutputStream(file); list.add(object1); list.add(object2); out.writeObject(list); out.close(); file.close(); System.out.println("object has been serialized");} catch(IOException ex){ ex.printStackTrace(); System.out.println("exception is caught");}try { FileInputStream file=new FileInputStream("C:\\Users\\SARANNIVAS\\Documents\\file\\obj"); ObjectInputStream in=new ObjectInputStream(file); ArrayList<Demo> list1=new ArrayList<>(); list1=(ArrayList<Demo>)in.readObject(); for(Demo d:list1) { System.out.println(d.a); System.out.println(d.b); }} catch(IOException ex) { System.out.println("IOException is caught"); }
1 回答
皈依舞
TA贡献1851条经验 获得超3个赞
我假设您正在尝试搜索您从文件中读回的数组列表。它是否正确?您可以使用类似...的方式搜索列表
public class DemoDemo {
public static void main(String[] args) {
Demo object1 = new Demo(100,"saran");
Demo object2 = new Demo(20 ,"nivas");
List<Demo> list=new ArrayList<>();
list.add(object1);
list.add(object2);
list
.stream()
.filter(d1 -> d1.name.equalsIgnoreCase("saran"))
.forEach(d2 -> System.out.println(d2.name + " of age " + d2.age));
}
}
class Demo {
public final int age;
public final String name;
public Demo (int age, String name) {
this.age = age;
this.name = name;
}
}
添加回答
举报
0/150
提交
取消