目录
案例要求:
实现思路:
代码:
总结:
案例要求:
实现思路:
创建一个包含学生姓名(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集合框架进行基本的数据分析和处理。