在 Java 中遍历地图

Iterating through Maps in Java

以下问题:

我有一个 TreeMap,它以字符串作为键,以 ArrayList 形式的集合作为值。 在字符串中,我保存了一家汽车租赁公司的客户姓名,在 ArrayLists 中,我得到了他们租过的所有汽车名称。 例如:

史密斯:[奥迪、宝马、马自达] 米勒:[奥迪、法拉利、大众]

现在我构建了第二个 TreeMap,其中字符串作为键,整数作为值。 字符串应为公司的所有汽车名称,整数应为他们曾经租用的次数。

我如何轻松地遍历第一个地图以节省第二个地图中的租车数量? 第一个 Map 中的 ArrayList 让我很头疼。

感谢您的帮助!

这部分我把数据放到了第二个Map中。 course 是第一个地图的名称,numberOfCars 是第二个地图的名称。

        int helpNumber = 0;
        for (Iterator<String> it = course.keySet().iterator(); it.hasNext(); ){
            Object key = it.next();
            if(course.get(key).contains(chooseName)){
                helpNumber++;
            }
            System.out.println((course.get(key).contains(chooseName)));
        }
        if(helpNumber == 1) {
            numberOfCars.put(chooseName, 1);
        } else if(helpNumber > 1) {
            int increasing = numberOfCars.get(chooseName);
            increasing++;
            numberOfCars.put(chooseName, increasing);
        }

在接下来的部分中,我尝试以这种方式打印它:

宝马:3 大众:2 奥迪:0 马自达:0

所以相同租金的组在一起,组内的车名按字母顺序排列。

    System.out.println("+++++++ car popularity +++++++");
    Object helpKey = null;
    for(Iterator<String> it = numberOfCars.keySet().iterator(); it.hasNext();) {
        Object key = it.next();
        if (helpKey == null){
            helpKey = key;
        }
        if(numberOfCars.get(key) > numberOfCars.get(helpKey)) {
            helpKey = key;
        }
    }
    int maxCount = numberOfCars.get(helpKey);
    for(int i = maxCount; i >= 0; i--) {
        for(Iterator<String> it = numberOfCars.keySet().iterator(); it.hasNext();) {
            Object key = it.next();
            if(numberOfCars.get(key) == maxCount) {
                System.out.println((String) key + ": " + numberOfCars.get(key));
            }
        }
    }

[我还不能发表评论] 由于您命名变量的方式,您提供的代码非常混乱。不要命名变量 SomeType helpXxx 以表明您需要有关此变量的帮助,如果您的代码呈现正确,人们将很容易区分哪些变量给您带来麻烦以及原因。

您收到的评论是正确的,说明您需要根据您遇到的具体问题而不是 "help me get this value" 提出问题。您的具体问题是当值的类型为 Collection 时遍历 Map 中包含的值。

就是说,因为我需要代表逃脱新用户堆栈交换监狱,这里是您的解决方案:

import java.util.*;

public class Test {
  public static void main(String[] args) {
    String[] customers = {
      "Mr PoopyButtHole", "Stealy", "Bird Person"
    };

    CarBrand audi = new CarBrand("Audi");
    CarBrand bmw = new CarBrand("BMW");
    CarBrand mazda = new CarBrand("Mazda");
    CarBrand vw = new CarBrand("VW");
    CarBrand ferrari = new CarBrand("Ferrari");

    // First Map: Customers paired with car brands they've rented
    SortedMap<String, List<CarBrand>> customerRentals =
      new TreeMap<String, List<CarBrand>>();
    // --- Fill the first map with info ---
    // For customer Mr PoopyButtHole
    List<CarBrand> mrPBHRentals = new ArrayList<>();
    Collections.addAll(mrPBHRentals, audi, bmw, mazda);
    customerRentals.put(customers[0], mrPBHRentals);
    // For customer Stealy
    List<CarBrand> stealyRentals = new ArrayList<>();
    Collections.addAll(stealyRentals, bmw, mazda, vw);
    customerRentals.put(customers[1], stealyRentals);
    // For customer Bird Person
    List<CarBrand> birdPersonRentals = new ArrayList<>();
    Collections.addAll(birdPersonRentals, audi, bmw, mazda, ferrari);
    customerRentals.put(customers[2], birdPersonRentals);

    // First Map contains 10 occurences of car brands across all the individual
    // arraylists paired to a respective customer

    // Second Map: Car brands paired with the amount of times they've been
    // rented
    // You don't actually need the second map to be a TreeMap as you want to
    // rearrange the results into your desired format at the end anyway
    Map<CarBrand, Integer> carBrandRentalCounts = new HashMap<>();
    // Place each CarBrand into carBrandRentalCounts and initialize the counts
    // to zero
    carBrandRentalCounts.put(audi, 0);
    carBrandRentalCounts.put(bmw, 0);
    carBrandRentalCounts.put(mazda, 0);
    carBrandRentalCounts.put(vw, 0);
    carBrandRentalCounts.put(ferrari, 0);

    // Get all the values (each ArrayList of carbrands paired to a customer) in
    // the first map
    Collection<List<CarBrand>> values = customerRentals.values();

    // Iterate through 'values' (each ArrayList of car brands rented)
    int total = 0;
    for(List<CarBrand> aCustomersRentals : values)
      for(CarBrand brand : aCustomersRentals) {
        // Get the current count for 'brand' in the second map
        Integer brandCurrentCount = carBrandRentalCounts.get(brand);
        // Increment the count for 'brand' in the second map
        Integer newBrandCount = brandCurrentCount+1;
        carBrandRentalCounts.put(brand, newBrandCount);

        total++;
      }

    // Init. a List with the entries
    Set<Map.Entry<CarBrand,Integer>> entries = carBrandRentalCounts.entrySet();
    List<Map.Entry<CarBrand,Integer>> listOfEntries =
      new ArrayList<Map.Entry<CarBrand,Integer>>(entries);
    // Sort the entries with the following priority:
    // 1st Priority: Highest count
    // 2nd Priority: Alphabetical order
    // NOTE: CustomSortingComparator implements this priority
    Collections.sort(listOfEntries, new CustomSortingComparator());

    // Print the results
    System.out.println("Count of rentals for each car brand:");
    for(Map.Entry<CarBrand, Integer> entry : listOfEntries)
      System.out.println("  " + entry.getKey() + " --> " + entry.getValue());
    System.out.println("Total:" + total);

    // Verify that our custom sorted entries are indeed being sorted correctly
    // Change the counts to be all the same
    for(Map.Entry<CarBrand, Integer> entry : entries)
      entry.setValue(10);
    // Resort the entries
    Collections.sort(listOfEntries, new CustomSortingComparator());
    // Print with the test entries
    System.out.println();
    System.out.println("With test entries where all counts are the same:");
    for(Map.Entry<CarBrand, Integer> entry : listOfEntries)
      System.out.println("  " + entry.getKey() + " --> " + entry.getValue());
    System.out.println("Total:" + total);
    // Change the counts so that the ordering is the alphabetically highest
    // brands followed by the lowest
    for(int i = listOfEntries.size()-1; i >= 0; i--)
      listOfEntries.get(i).setValue(i);
    // Resort the entries
    Collections.sort(listOfEntries, new CustomSortingComparator());
    // Print with the test entries
    System.out.println();
    System.out.println("with test entries where the \"bigger\" car brands " +
      "alphabetically have higher counts:");
    for(Map.Entry<CarBrand, Integer> entry : listOfEntries)
      System.out.println("  " + entry.getKey() + " --> " + entry.getValue());
    System.out.println("Total:" + total);
  }
}

class CustomSortingComparator
implements Comparator<Map.Entry<CarBrand,Integer>> {
  public int compare(Map.Entry<CarBrand, Integer> entry1,
                     Map.Entry<CarBrand, Integer> entry2) {
    CarBrand brand1 = entry1.getKey();
    CarBrand brand2 = entry2.getKey();
    int brandResult = brand1.compareTo(brand2);
    Integer count1 = entry1.getValue();
    Integer count2 = entry2.getValue();
    int countResult = count1.compareTo(count2);

    return
      countResult > 0 ?
        -1 : countResult < 0 ?
          1 : brandResult < 0 ?  // <-- equal counts here
            -1 : brandResult > 1 ?
              1 : 0;
  }
}

// DONT WORRY ABOUT THIS CLASS, JUST MAKES IT EASIER TO IDENTIFY WHAT'S GOING
// ON IN THE FIRST MAP
class CarBrand implements Comparable<CarBrand> {
  public final String brand;

  public CarBrand(String brand) { this.brand = brand; }

  @Override
  public int compareTo(CarBrand carBrand) {
    return brand.compareTo(carBrand.brand);
  }

  @Override
  public boolean equals(Object o) {
    // IF o references this CarBrand instance
    if(o == this) return true;
    // ELSE IF o is of type CarBrand, perform equality check on field 'brand'
    else if(o instanceof CarBrand) {
      CarBrand obj = (CarBrand)o;
      // IF the brands are equal, o is equal to this CarBrand
      if(brand.equals(obj.brand)) return true;
    }

    return false;
  }

  @Override
  public String toString() { return brand; }

  @Override
  public int hashCode() { return brand.hashCode(); }
}

输出:

Count of rentals for each car brand:
  BMW --> 3
  Mazda --> 3
  Audi --> 2
  Ferrari --> 1
  VW --> 1
Total:10

With test entries where all counts are the same:
  Audi --> 10
  BMW --> 10
  Ferrari --> 10
  Mazda --> 10
  VW --> 10
Total:10

with test entries where the "bigger" car brands alphabetically have higher counts:
  VW --> 4
  Mazda --> 3
  Ferrari --> 2
  BMW --> 1
  Audi --> 0
Total:10

无需任何更改或额外导入即可编译和运行。

更多信息

看来您对如何获得预期结果想得太多了,或者您没有很好地掌握地图 class,因此只能通过黑客攻击。我们都这样做了……我们都讨厌 12 小时后的自己这样做。考虑清楚:)

确定主要问题:遍历第一个映射中包含的所有值。

在抓住问题之前,不要陷入实施细节,又名:

  • 地图中值 V 的类型,在本例中为 ArrayList
  • 正在使用什么类型的地图

您的代码中没有 return 的要点是您尝试计算第一个地图值中汽车品牌的出现次数并将这些计数存储到第二个地图中。这里有一个 "recipe" 代码提示来帮助你处理它。

  1. 从 CustomerRentals 获取所有值(地图 1)
    • Collection<ArrayList<String>> eachCustomersRentals = CustomerRentals.values();
  2. 遍历每个客户的租金,存储每个客户的总计数 汽车品牌
    • for(ArrayList<String> aCustomersRentals : eachCustomersRentals) {...}
    • {...}中首先嵌套一个增强的for-each循环迭代 aCustomersRentals
    • 然后在嵌套循环中计算特定客户的品牌 租用,将每个相应的计数存储在范围内的变量中 方法的(也就是外部 for-each 构造之外)
  3. 初始化第二张地图
  4. 将每个汽车品牌及其计数放入第二张地图

如果您不知道如何实现自定义比较器来为您抽象出细节,那么您想要实现的输出排序将会非常混乱。如果一定要做这种排序,好好看看Comparator和Comparable接口文档(Google Comparator/Comparable),然后分析我是如何实现的。