在列表中进行迭代时,将一个或多个匹配项组合在一起

问题描述

如果我需要遍历列表并尝试将元素分组在一起,那么最好的方法是什么?

例如,我们有以下对象要循环通过:

People
  |---Person
  |     -FirstName: Jimmy
  |     -LastName: Ward
  |     -Address1: 1 Main Street
  |     -Town: Yipee
  |     -Country: Canada
  |     -Postcode: ABC
  |---Person
  |     -FirstName: Johnny
  |     -LastName: Jones
  |     -Address1: 21 Jump Street
  |     -Town: SomeTownie
  |     -Country: Ireland
  |     -Postcode: ZZZ
  |---Person
  |     -FirstName: Vinny
  |     -LastName: McWhinney
  |     -Address1: 11 Blah Lane 
  |     -Town: Pastaville
  |     -Country: Italy
  |     -Postcode: ALO
  |---Person
  |     -FirstName: Tommy
  |     -LastName: Jones
  |     -Address1: 21 Jump Street
  |     -Town: SomeTownie
  |     -Country: Ireland
  |     -Postcode: ZZZ
  |---Person
  |     -FirstName: Wendy
  |     -LastName: Ward
  |     -Address1: 1 Main Street
  |     -Town: Yipee
  |     -Country: Canada
  |     -Postcode: ABC
  |---Person
  |     -FirstName: Jenny
  |     -LastName: Bloggs
  |     -Address1: 1 Yadda Road
  |     -Town: Blahdeblah
  |     -Country: Ireland
  |     -Postcode: XYZ

我需要遍历每个人,并创建一个由具有相同地址和相同姓氏的人组成的小组。

例如,它以Jimmy开头,遍历列表以查找具有相同地址和姓氏的任何人,只有Wendy匹配,因此他们都被分组在一起。接下来是约翰尼,汤米是唯一的对手。

遍历列表中的其余人员时,我们不想对Wendy或Tommy进行相同的处理(因为他们已经分组)。因此,我们需要从原始列表中删除匹配的内容,或者以某种方式插入地图?

我在想一个while循环,然后在for循环中查找任何匹配项。免责声明:此提议的解决方案用于删除那些匹配项,因此可能与预期不符。

例如:

while (!originalPersonList.isEmpty()) {
  ArrayList<Person> newGroup = new ArrayList<Integer>();
  List<Integer> indexToRemove = new ArrayList<Integer>();
  newGroup.add(0);
  indexToRemove.add(0);
  for (int i=1; i < originalPersonList.size(); i++) {
    if (originalPersonList.get(0).Address1().equals( originalPersonList.get(i).Address1())
      && originalPersonList.get(0).Town().equals(originalPersonList.get(i).Town())
      && originalPersonList.get(0).Country().equals( originalPersonList.get(i).Country())
      && originalPersonList.get(0).Postcode().equals( originalPersonList.get(i).Postcode()
      && originalPersonList.get(0).Lastname().equals( originalPersonList.get(i).Lastname()) 
    {
       indexToRemove.add(i);
       newGroup.add(i);
    }
  }
  originalPersonList.removeAll(indexToRemove);
}

这就是我要去的方向,但是我觉得那里可能会有一个更优雅的解决方案?

我只能使用Java7。

我也尝试搜索类似的问题,但是在这种情况下没有任何匹配项。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)