gpt4 book ai didi

java - 不使用数组编写此方法的另一种方法

转载 作者:行者123 更新时间:2023-12-01 21:47:49 26 4
gpt4 key购买 nike

是否有另一种方法可以在不使用数组的情况下编写此方法,例如使用 foreachif 语句?我只是想看看有没有更简单的写法。

/**
* Write a method that prints the number of movies of each star rating
*/
public void printRatingReport()
{
int[] numMovies = new int[5];
for (Movie m : movies){
numMovies[m.getStarRating()]++;
}

for (int i=0; i<=4; i++){
System.out.println(i+ " star movies " + numMovies[i]);
}
}

最佳答案

使用 Java 8 你可以做到

SortedMap<StarRating, Long> starCount = movies.stream()
.collect(Collectors.groupingBy(m -> m.getStarRating(),
TreeMap::new, Collectors.counting());

starCount.forEach((rating, count) -> System.out.println(rating + " star movies " + count));

关于java - 不使用数组编写此方法的另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com