简体   繁体   English

Java-从txt文件中查找特定ID并返回该行详细信息的方法

[英]Java - method to lookup a specific ID from txt file and return that line details

I am writing a method to lookup a specific ID that is stored within a txt file. 我正在编写一种方法来查找存储在txt文件中的特定ID。

These details are assigned to an arrayList titled list, if the lookup string matches the data stored in list then it reads the id,firstname,surname (IE the whole line of the txt file) and then creates an instance of another class profile. 这些详细信息将分配给标题为arrayList的列表,如果查找字符串与存储在列表中的数据匹配,则它将读取id,firstname,surname(即txt文件的整个行),然后创建另一个类概要文件的实例。

I then want to add this lookup data to a new arrayList titled lookup then to output it. 然后,我想将此查询数据添加到标题为lookup的新arrayList中,然后将其输出。 I have the below method however, it does not work and just jumps to my else clause. 我有以下方法,但是它不起作用,只是跳转到我的else子句。 Could anyone tell me where i'm going wrong and how to fix would be appreciated. 谁能告诉我我要去哪里错误以及如何解决。 Thanks. 谢谢。

Could you instead use a TupleMap for the same effect? 您可以改用TupleMap来达到相同的效果吗?

// create our map Map peopleByForename = new HashMap>(); //创建地图Map peopleByForename = new HashMap>();

// populate it peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith", new Person("Bob Jones")); //填充它personByForename.put(“ Bob”,new Tuple2(new Person(“ Bob Smith”,new Person(“ Bob Jones”)));

// read from it Tuple bobs = peopleByForename["Bob"]; //从中读取元组鲍勃= peopleByForename [“ Bob”]; Person bob1 = bobs.Item1; 人bob1 = bobs.Item1; Person bob2 = bobs.Item2; 人bob2 = bobs.Item2;

Then an example of reading the key:value from the txt file can be found here : Java read txt file to hashmap, split by ":" using Buffered Reader. 然后,可以在此处找到从txt文件读取key:value的示例: Java将txt文件读取为hashmap,使用Buffered Reader 将其分割为“:”

If you are using Java8, you can use Lambda to help you. 如果您使用的是Java8,则可以使用Lambda来帮助您。 Just replace this line: 只需替换此行:

    if(list.contains(IDlookup))

to this one: 对此:

    boolean containsId = list.stream().anyMatch((Profile p) -> p.getId().equals(IDlookup));
    if (containsId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM