在HashMap中搜索多个值

时间:2015-11-16 22:57:05

标签: java loops search arraylist hashmap

我将联系人列表存储为" Person"类型的HashMap,并希望有一个搜索功能,我可以在其中搜索HashMap,然后返回名字的所有人" John& #34;例如,谁住在美国。我的想法是只创建一个PersonList的ArrayList并循环添加每个值:

  Map<Person, Person> hm = new HashMap<Person, Person>();
  ArrayList<String> result = new ArrayList<String>();

  Enumeration num= hm.keys();
  String name = "John";
  String location = "USA"; 

  while (num.hasMoreElements()) {
         Person person = (Person) num.nextElement();

         if(person.name.equals(name) && person.location.equals(location))
         {
            result.add(person);
         }

我只是想知道这是否可以正常工作,或者是否有一些更好的方法可以忽略我。

由于

5 个答案:

答案 0 :(得分:0)

我建议您使用密钥上的Enumerable语法,而不是使用for

   for ( Person person : hm.keys() )
   {
       // Your if statement goes here
   }

答案 1 :(得分:0)

你真的想要:

Set<Person> hm = new HashSet<Person>();
for(Person person: hm)
{
    // your logic here
}

如果出于某种原因你还没有在地图上设置死机,请按照以下方式迭代:

for(Map.entry<Person, Person> entry: hm.entrySet())
{
    // use entry.getKey() and entry.getValue()
}

答案 2 :(得分:0)

没有结构上更好的解决方案,因为HashMap以任意,不透明的顺序包含其键,任何不完全知道内部的算法都不能使用它。因此,没有干净的方法来遍历所有元素(键)。

我所建议的风格改进已经显示为@WW。

答案 3 :(得分:0)

除非您确实需要映射Person个对象,否则我建议您使用Set而不是Map

Set<Person> people = new HashSet<Person>();

Java 8为您提供了一种创建过滤集的好方法:

Set<Person> subset = people.stream()
    .filter(p -> p.getName().equals(name))
    .filter(p -> p.getLocation().equals(location))
    .collect(Collectors.toSet());

如果您需要某些预定义的搜索条件,则可以将其创建为方法:

class Person {
    public static Predicate<Person> hasNameAndLocation(String name, Location location) {
        return person -> person.name.equals(name) && person.location.equals(location);
    }
}

这使您的过滤代码更好,并避免使用getter:

.filter(Person.hasNameAndLocation("Fred", Country.USA))

如果您需要非常高的性能(可能只需要数百万项或每秒数千次搜索),那么解决方案是使用单独的地图来快速进行预定义搜索:

Map<String, Set<Person>> nameMap;
Map<Location, Set<Person>> locationMap;

Set<Person> subset = nameMap.get("Fred")
    .filter(locationMap.get(Country.USA)::contains))
    .collect(Collectors.toSet());

这可能非常快,但是由于您有多个集合可以保持最新,因此会使代码更加复杂。除非您有明显的性能要求,否则不要这样做。

答案 4 :(得分:0)

    Map<String, Integer> myMap = new TreeMap<String, Integer>();
    List<Entry<String, Integer>> listOfEntries = new ArrayList<Entry<String, Integer>>(myMap.entrySet());

     for(int i=0;i<listOfEntries.size();i++){
//listOfEntries.get(0).getValue(), put your condition for comparison   
            if(listOfEntries.get(0).getValue()==listOfEntries.get(i).getValue()){
                        System.out.println(listOfEntries.get(i));
                    }
                }