目錄
案例要求:
實現思路:
代碼:
總結:
案例要求:
實現思路:
創建一個包含學生姓名(String)和選擇地址變量(集合)的實體類,然后將題干數據封裝到集合,然后進行stream操作
代碼:
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;//TIP 要<b>運行</b>代碼,請按 <shortcut actionId="Run"/> 或
// 點擊裝訂區域中的 <icon src="AllIcons.Actions.Execute"/> 圖標。
public class Main {static Scanner sc = new Scanner(System.in);public static void main(String[] args) {List<Student> students = new ArrayList<>();students.add(new Student("張全蛋兒", List.of("農家樂", "野外拓展")));students.add(new Student("李二狗子", List.of("轟趴", "野外拓展", "健身房")));students.add(new Student("翠花", List.of("野外拓展")));students.add(new Student("小帥", List.of("轟趴", "健身房")));students.add(new Student("有容", List.of("農家樂")));// 1. 統計每個去處的人數并找出投票最多的去處Map<String, Integer> placeCountMap = new HashMap<>();students.forEach(student -> student.getChoices().forEach(choice -> {placeCountMap.put(choice, placeCountMap.getOrDefault(choice, 0) + 1);}));String mostPopularPlace = placeCountMap.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse(null);System.out.println("每個去處的人數:");placeCountMap.forEach((place, count) -> System.out.println(place + ":" + count));System.out.println("投票最多的去處是:" + mostPopularPlace);// 2. 找出沒有選擇投票最多去處的學生List<String> studentsWithoutMostPopular = students.stream().filter(student ->!student.getChoices().contains(mostPopularPlace)).map(Student::getName).collect(Collectors.toList());System.out.println("沒有選擇投票最多去處的學生:" + studentsWithoutMostPopular);}
}
總結:
這篇文章展示了一個簡單的Java程序,用于統計學生選擇的去處情況。程序首先創建了5個學生對象及其選擇的活動去處,然后:1)統計每個去處的人數并找出投票最多的去處;2)找出沒有選擇最受歡迎去處的學生名單。程序使用了集合操作和流處理來實現統計功能,最終輸出每個去處的人數統計、最受歡迎去處以及未選擇該去處的學生名單。這個案例演示了如何使用Java集合框架進行基本的數據分析和處理。