java - 在 Java 中迭代 Map

标签 java arraylist collections maps treemap

以下问题:

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

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

现在我构建了第二个 TreeMap,其中字符串作为键,整数作为值。 字符串是公司的所有汽车名称,整数是它们被租赁的次数。

我如何轻松地迭代第一个 map 以节省第二个 map 中的租用汽车数量? 第一个 Map 中的 ArrayList 给我带来了问题。

感谢您的帮助!

在这部分我将数据放入第二个Map中。 course 是第一个 Map 的名称,numberOfCars 是第二个 Map 的名称。

        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表明您需要有关此变量的帮助,如果您的代码正确呈现,人们将很容易区分哪些变量给您带来麻烦以及原因。

您收到的评论是正确的,即您需要根据您遇到的具体问题提出问题,而不是“帮助我获取此值”。您的具体问题是当值的类型为 Collection 时,迭代 Map 中包含的值。

也就是说,因为我需要代表来逃避新用户堆栈交换 jail ,所以这是您的解决方案:

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

它可以编译并运行,无需任何更改或额外导入。

更多信息

看起来您过度思考如何获得所需的结果,或者您没有很好地掌握 Map 类,因此只是在破解。我们都这么做了……12小时后我们都讨厌自己这么做。想清楚了:)

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

在掌握问题之前,不要陷入实现细节,又名:

  • Map 中值 V 的类型,在本例中为 ArrayList
  • 使用什么类型的 map

代码中的不返回点是当您尝试计算第一个 map 的值中汽车品牌的出现次数并将这些计数存储到第二个 map 时。这是一个带有代码提示的“食谱”,可以帮助您处理它。

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

如果您不知道如何实现自定义比较器来为您抽象出详细信息,那么您想要实现的输出排序将会非常非常困惑。如果您必须进行这种排序,请仔细阅读 Comparator 和 Comparable 接口(interface)文档 (Google Comparator/Comparable ),然后分析我是如何实现的。

关于java - 在 Java 中迭代 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047814/

相关文章:

java - 将正在运行的java程序的输出保存为String[]

java - ArrayList 对象在 java android 的 ListView 上返回一行

java - 如何检索 ArrayList<Object> 中包含两个不同对象类型 arraylist 的值?

java - 使用 ListView 适配器

javascript - Backbone.js:如何通过模型 ID 数组过滤对象集合?

占用内存最少的 Java 对象

java - 使用 JAXB 解码在下面的代码中给出 null 吗?

java - Android TimeZone.getAvailableIDs() 产生奇怪的字符串

java - 使用 Tomcat 流媒体

java - 代号一本地通知不适用于 ios