[英]How to create an ArrayList for every unique column value of a .txt file in Java?
I'm writing a program that reads a .txt file line by line, and I want to create for every 'unique' value of one column, an ArrayList
. 我正在编写一个程序,逐行读取.txt文件,并且我想为每一列的“唯一”值创建一个
ArrayList
。
What the .txt file looks like: .txt文件如下所示:
NAME AGE COUNTRY PHONE NUMBER
Peter 28 USA 00112233
John 25 England 11223344
Justin 22 Australia 22334455
Daisey 24 Canada 33445566
Harry 27 England 44556677
Laura 25 England 55667788
Gary 28 USA 66778899
For example, I want to create for each nationality an ArrayList, with the corresponding names as elements. 例如,我想为每个国籍创建一个ArrayList,以相应的名称作为元素。
So, this: 所以这:
ArrayList USA: Peter, Gary
ArrayList England: John, Harry, Laura
ArrayList Australia: Justin
ArrayList Canada: Daisey
I don't want to create the ArrayLists
myself, before running the program. 在运行程序之前,我不想自己创建
ArrayLists
。 Because the real column I'm talking about has lots of different values, so lots of ArrayList
should be made. 因为我要说的实际列具有很多不同的值,所以应该制作很多
ArrayList
。 Does anyone know how I can let the program create an Arraylist
for every unique nationality, and add the corresponding names to this ArrayList
? 有谁知道我如何让程序为每个唯一的国籍创建一个
Arraylist
,并将相应的名称添加到该ArrayList
?
Well,it's easier to work with domain objects like: 好吧,使用像这样的域对象会更容易:
class User {
String name;
String country;
int age;
String phone;
// getters and setters omitted
}
Somewhere in your code there will be method like: 在代码中的某处将有类似以下方法:
List<User> readfromFile(String fileName) {
// create User for each read line
}
And then use Stream Api to group by needed column like: 然后使用Stream Api按所需列进行分组,例如:
Map<String, List<User>> usersByCountry = users.stream().collect(Collectors.groupingBy(User::getCountry));
If you want just user names grouped by country: 如果只想按国家/地区分组用户名:
Map<String, List<String>> userNamesByCountry = users.stream().collect(Collectors.groupingBy(User::getCountry, LinkedHashMap::new, Collectors.mapping(User::getName, Collectors.toList())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.