练习1:
//需求:创建一个HashMap集合,键是学生对象Student,值是籍贯,储存3个键值对对象并遍历,要求同性别,同年龄位同一个学生
//核心点:如果是键存储自定义对象,需要重写equal和Hashcode方法
//创建一个map集合
HashMap<Student,String> hashMap=new HashMap<>();
//创建对象
Student student1 = new Student("张三", "25");
Student student2= new Student("李四", "35");
Student student3 = new Student("王五", "45");
//添加元素
hashMap.put(student1,"江西");
hashMap.put(student2,"万年");
hashMap.put(student3,"苏桥");
//键值对遍历
Set<Map.Entry<Student, String>> entries = hashMap.entrySet();
for (Map.Entry<Student, String> entry : entries) {
Student key = entry.getKey();
String value = entry.getValue();
System.out.println(key+value);
}
System.out.println("-------------------------------------------------------------");
//键遍历
Set<Student> students = hashMap.keySet();
for (Student key : students) {
String value = hashMap.get(key);
System.out.println(value+key);
}
System.out.println("-------------------------------------------------------------");
//lambda表达式遍历
hashMap.forEach(new BiConsumer<Student, String>() {
@Override
public void accept(Student student, String s) {
System.out.println(student+s);
}
});
}
}
class Student{
private String name;
private String age;
public Student() {
}
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
//关于值,重写方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(age, student.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
代码实现:
import java.util.*;
public class map集合练习2 {
public static void main(String[] args) {
//定义一个数组记录集合
String[] array={"A","B","C","D"};
//定义一个集合记录景点次数
ArrayList<String> arrayList=new ArrayList<>();
//利用随机数模拟80个同学投票,并且把投票结果存储起来
Random random=new Random();
for (int i = 0; i <80 ; i++) {
int j = random.nextInt(array.length);
arrayList.add(array[j]);
}
//将投票的次数放入到HashMap中
HashMap<String,Integer> map=new HashMap<>();
//遍历集合中的元素
for (String name : arrayList) {
//判断当前景点在集合中是否存在
if (map.containsKey(name)){
//存在
//获取当前景点被投票的次数
int count = map.get(name);
//代表当前景点又被投了一次
count++;
//将新的投票结果加入
map.put(name,count);
}else {
//不存在
map.put(name,1);
}
}
//判断最大值
//记录最小值
int max=0;
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
int count=entry.getValue();
if (count>max){
max=count;
}
}
System.out.println(map);
System.out.println(max);
//将最大票的景点打印出来
for (Map.Entry<String, Integer> entry : entries) {
int count=entry.getValue();
if (count==max){
System.out.println(entry.getKey());
}
}
}
}