import java.util.Objects;
public class student {
private String name;
private int age;
public student() {
}
public student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int 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 age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String toString() {
return "student{name = " + name + ", age = " + age + "}";
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
public class demo {
public static void main(String[] args) {
HashMap<student,String> hm=new HashMap<>();
//hashmap的键存的是自定义 要去重写JavaBean中的hashcode和equals
//创建学生对象
student s1=new student("ooo",12);
student s2=new student("dam",19);
student s3=new student("xm",18);
//相同的就覆盖掉了
student s4=new student("xm",18);
hm.put(s1,"河南");
hm.put(s2,"北京");
hm.put(s3,"上海");
hm.put(s4,"苏州");
//遍历 (键找值)
Set<student> keys = hm.keySet();
for (student key : keys) {
String value = hm.get(key);
System.out.println(key+"="+value);
}
System.out.println("--------------------------");
//遍历(键值对)
Set<Map.Entry<student, String>> entries = hm.entrySet();
for (Map.Entry<student, String> entry : entries) {
student key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
}
System.out.println("--------------------------");
//lambda遍历
hm.forEach((student, s)-> System.out.println(student+"="+s)
);
}
}
import java.util.*;
public class demo {
public static void main(String[] args) {
//定义数组存四个地方
String arr[]={"a","b","c","d"};
//80个学生随机投票 扔到集合中
ArrayList<String> arrayList=new ArrayList<>();
Random r=new Random();
for (int i = 0; i < 80; i++) {
int index = r.nextInt(arr.length);
arrayList.add(arr[index]);
}
//利用hashmap来计数 因为太多了计数器不方便
HashMap<String,Integer>hm=new HashMap<>();
//遍历arraylist
for (String name : arrayList) {
//看看景点是不是第一次存在
if (hm.containsKey(name)){
//存在 则次数加一
//获取存在的次数
int count = hm.get(name);
//加一
count++;
//加一后放入值中
hm.put(name,count);
}else {
//不存在就生成一个景点的键 再值为1
hm.put(name,1);
}
}
System.out.println(hm);
//最大值
int max=0;
Set<Map.Entry<String, Integer>> entries = hm.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
Integer value = entry.getValue();
if (value>max){
max=value;
}
}
System.out.println(max);
//最大值对应的 景点也就是键
for (Map.Entry<String, Integer> entry : entries) {
//获取值
Integer value = entry.getValue();
//拿值与上方最大值进行比较
if (value==max){
//最大值对应的 键输出
System.out.println(entry.getKey());
}
}
}
}