以下问题:
我有一个带有字符串的TreeMap作为键,以及ArrayLists形式的集合作为值。 在Strings中我保存了一家汽车租赁公司的客户姓名,在ArrayLists中,我已经获得了他们租过的所有汽车名称。 例如:
史密斯:[奥迪,宝马,马自达] 米勒:[奥迪,法拉利,大众]现在我构建了第二个TreeMap,其中Strings为Keys,Integers为Values。 字符串应该是公司的所有汽车名称,而整数是它们租用的次数。
如何轻松迭代第一张地图以节省第二张地图中的租车数量? 第一张Map里面的ArrayList让我有问题。
感谢您的帮助!
在这部分中,我将数据放入第二个Map。当然是第一个Map的名称,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));
}
}
}
答案 0 :(得分:1)
[我无法发表评论] 由于您为变量命名的方式,您提交的代码非常混乱。不要将变量命名为SomeType helpXxx
以表明您需要有关此变量的帮助,如果您的代码正确显示,人们很容易区分哪些变量导致您遇到麻烦以及原因。
您收到的评论是正确的,表明您需要根据您所遇到的具体问题提出问题,而不是“帮助我获得此价值”。当值为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
这可以编译并运行,无需任何更改或额外导入。
看起来你过分思考如何获得理想的结果,或者你没有很好地掌握Map类,因此只是在破解你的方式。我们都这样做了...... 12个小时后我们都讨厌这样做。仔细考虑一下:))
确定主要问题:迭代第一张地图中包含的所有值。
在您掌握问题之前,请不要了解实施细节,例如:
您的代码中无法返回的点是您尝试在第一张地图的值中计算汽车品牌的出现次数并将这些计数存储到第二张地图中。这是一个带有代码提示的“配方”,可以帮助您处理它。
Collection<ArrayList<String>> eachCustomersRentals = CustomerRentals.values();
for(ArrayList<String> aCustomersRentals : eachCustomersRentals) {...}
{...}
中首先嵌套一个迭代的增强for-each循环
aCustomersRentals 如果您不知道如何实现自定义Comparator来为您抽象细节,那么您希望为输出实现的排序将非常混乱。如果您必须进行此排序,请仔细查看Comparator和Comparable接口文档(Google Comparator / Comparable),然后分析我是如何实现它的。