在不使用Array的情况下编写此方法的另一种方法

时间:2016-03-01 20:43:53

标签: java arrays methods

是否有其他方法可以在不使用数组的情况下编写此方法,例如使用for eachif语句?我只是想看看是否有更简单的方法来编写它。

/**
 * 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]);
    }
}

2 个答案:

答案 0 :(得分:3)

使用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));

答案 1 :(得分:0)

使用枚举。这样你可以使用foreach并可能将评级系统从5星改为2,6或更多,因为代码会更具凝聚力。

enum Stars {
    One, Two, Three, Four, Five
}

public void starRatingReport() {
    for (Stars starRating : Stars.values()) {
        int number = 0;
        for (Movie movie : movies) {
            if (movie.getRating() == starRating) {
                number++;
            }
        }
        System.out.println(number + " Movies with rating " + starRating);
    }
}

你也可以使用属性,但在我看来,它们有点复杂。

相关问题