2017-05-28 58 views
0

我试着收集到一个列表中的所有从我的数据库具有相同的名称,以便在位置,即时通讯使用该做的事:如何在我的数据库中按名称过滤位置?

public static List<Location> searchRepe(List<Location>ls){ 
     List<Location>res=new ArrayList<Location>(); 
     for(Location l:ls){ 
      ls.remove(l); 
if(ls.stream().anyMatch(x>x.getProvinceName().equals(l.getProvinceName()))){ 
       res.add(l);} 
      ls.add(l);  
     } 
     return res; 
    } 

错误:异常线程“main” java.util.ConcurrentModificationException

我先删除列表的位置,然后检查是否有另一个具有相同名称的位置。在检查了位置名称是否在列表中后,我将它添加到我的res列表中。在任何情况下,我会始终保持原始列表相同,因为在检查后,我将元素读入列表。我知道错误是由于我在每次迭代中删除并添加的,但如果在每次迭代中删除并添加相同的元素,则列表的大小将始终相同。

有人能告诉我一个更好的方法来做到这一点?如果有可能使用java8

回答

0

foreach语句使用Iterator检索项目,Iterator不能直接删除项目,否则该方法将抛出ConcurrentModificationException

for (int index = 0; index < list.size(); index++) { 
    if(condition){ 
     list.remove(index); 
     index--; 
    } 
} 

在你的问题,你可以使用Multimap这是Guava图书馆新的集合类型,像这样:

public static List<Location> searchRepe(List<Location>ls){ 
    Multimap<String,Location> locationMap = HashMultimap.create(); 
    for (Location l : ls) { 
     locationMap.put(l.getProvinceName(),l); 
    } 
    List<Location> result=new ArrayList<>(); 
    for (Map.Entry<String, Collection<Location>> entry : locationMap.asMap().entrySet()) { 
     Collection<Location> value = entry.getValue(); 
     if(value.size()>1){ 
      Location next = value.iterator().next(); 
      result.add(next); 
     } 
    } 
    return result; 
} 

注意这个,所以你可以通过下面的方法从列表中移除项行locationMap.put(l.getProvinceName(),l)put方法的结果取决于Location类中的equals方法。

0

如果你绝对想使用流和java8,我相信这是正确的解决方案。 只是过滤的ProvinceName多个

public static List<Location> searchRepe(List<Location> ls) { 

    return ls.stream() 
      .filter(
        location -> ls.stream() 
            .map(Location::getProvinceName) 
            .filter(n -> Objects.equals(n, location.getProvinceName())) 
            .count() > 1L 
      ) 
      .collect(Collectors.toList()); 
} 

或使用分组由

public static List<Location> searchRepe(List<Location> ls) { 

    return ls.stream() 
      .collect(Collectors.groupingBy(Location::getProvinceName)) 
      .entrySet() 
      .stream() 
      .map(Map.Entry::getValue) 
      .filter(entry -> entry.size() > 1) 
      .map(entry -> entry.get(1)) 
      .collect(toList()); 
} 
+0

第方法,其中基于事件的计数的所有元素的伟大工程提供了我想要的清单与所有具有位置他们的省名是共同的。第二种方法只是根据其省份名称收集出现多次的地点。 非常感谢你Neonailol –

相关问题