关于java中map存储多行的小程序(一键对多值)

这篇博客详细介绍了如何在Java中使用Map数据结构来存储多行数据,特别是实现一键对应多个值的功能。通过实例代码展示了一种高效的方法来管理和操作这种数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//将键值value设置为Student对象,Student对象可自行设置,代码如下:
public class Student {
	private int id;
	private String name;
	private int score;
	
	public void setId(int id){
		this.id=id;	
	}
	
	public void setName(String name){
		this.name=name;	
	}
	
	public void setScore(int score){
		this.score=score;	
	}
	
	public Integer getId(){
		return id;
	}
	
	public String getName(){
		return name;
	}
	
	public Integer getScore(){
		return score;
	}
}
</pre><p>类mapTest2:</p><pre name="code" class="java">package practice;

import java.util.*;
import java.util.Map.Entry;

public class mapTest2 {
	
	public static void main(String[] args) {

	Student obj1=new Student();
	obj1.setId(1);
	obj1.setName("xl");
	obj1.setScore(99);
	
	Student obj2=new Student();
	obj2.setId(2);
	obj2.setName("cq");
	obj2.setScore(98);
	
	Student obj3=new Student();
	obj3.setId(3);
	obj3.setName("xh");
	obj3.setScore(97);
	
	HashMap<String, Student> map = new HashMap<String, Student>();
	map.put("1", obj1);  
	map.put("2", obj2);
	map.put("3", obj3);
	List<Map<String, Student>> list = new ArrayList<Map<String, Student>>();  
	list.add(map); 
	
	for (Entry<String, Student> entry : map.entrySet()) {
	    if(entry.getValue().getScore()==97){
	    Student obj=entry.getValue();
	    obj.setScore(100);
	    String i=entry.getKey();
	    map.put(i, obj);	
	    System.out.println("Key = " + entry.getKey() + ",学号 = " + entry.getValue().getId()+ ",姓名 = "+ entry.getValue().getName()+",成绩 = "+entry.getValue().getScore());
	    }
	    else  System.out.println("Key = " + entry.getKey() + ",学号 = " + entry.getValue().getId()+ ",姓名 = "+ entry.getValue().getName()+",成绩 = "+entry.getValue().getScore());  
	      
	    }  	
}
}

输出如下图:





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值