我有一个包含帐单 ID
和电子邮件
数据的列表。
账单 ID 和电子邮件可以在列表中重复。
这是我的列表数据:
List<Bill> billings = new ArrayList<Bill>();
Bill bill1 = new Bill("90008489", "demo@gmail.com");
Bill bill2 = new Bill("90008489", "oke@sample.com");
Bill bill3 = new Bill("90008489", "welcom@gmail.com");
Bill bill4 = new Bill("90008490", "hore@yahoo.com");
Bill bill5 = new Bill("90008490", "fix.it@demo.co.id");
Bill bill6 = new Bill("90008491", "yuhuuu@demo.co.id");
billings.add(bill1);
billings.add(bill2);
billings.add(bill3);
billings.add(bill4);
billings.add(bill5);
billings.add(bill6);
这是我为 Bill 准备的 Java 类:
public class Bill {
private String id;
private String email;
private List<String> emails;
public Bill(String id, String email) {
super();
this.id = id;
this.email = email;
}
public Bill(String id, List<String> emails) {
super();
this.id = id;
this.emails = emails;
}
... Getter and Setter
我想按帐单 ID 对该列表数据进行分组。 如果找到相同的帐单 ID,我想合并电子邮件数据。
我不知道何时构建它。这是我的代码。
List<Bill> newBillings = new ArrayList<Bill>();
for (int i = 0; i < (billings.size() - 1); i++) {
List<String> emails = new ArrayList<String>();
emails.add(billings.get(i).getEmail());
//System.out.println(billings.get(i+1).getId());
if (billings.get(i).getId() == billings.get(i + 1).getId()) {
emails.add(billings.get(i+1).getEmail());
}
}
for (Bill bill : newBillings) {
System.out.println(bill.getId());
for (String email : bill.getEmails()) {
System.out.print(email + ",");
}
System.out.println("\n-----");
}
我的预期结果是:
90008489 - [demo@gmail.com, oke@sample.com, welcome@gmail.com]
90008490 - [hore@yahoo.com, fix.it@demo.co.id]
90008491 - [yuhuuu@demo.co.id]
最佳答案
我想说你为此使用了错误的数据结构。
我会完全重写它并使用 Map<String, List<String>>
因为它会更合适,因为您需要将每个 id 映射到邮件列表。
Map<String, List<String>> map = new HashMap<>();
for(Bill b : billings) {
List<String> list = map.get(b.getId()); //try to get the list with the specified id
if(list == null) { //if the list is null, it means that there is no mapping yet in the map, so create one
list = new ArrayList<>();
map.put(b.getId(), list);
}
list.add(b.getEmail()); //add the corresponding email to the list
}
可以翻译成Java 8风格
Map<String, List<String>> map = billings.stream()
.collect(groupingBy(Bill::getId, mapping(Bill::getEmail, toList())));
关于java - 按特定值分组列出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27522428/