和二楼的意见相符,补充一下,具体是这样的:可以Map<String,double> map = new HashMap(); 往里存值时,map.put("物理",95);map.put("数学",100);这时map.put("物理",100);就插不进去了,三楼的方法也很好,都可以的!
使用HashMap 使用键值对
首先遍历List,然后将遍历的元素放入到HashMap类型中的map中,然后再讲map中的内容放入到list中去。 代码如下: //KeyValue类 public class KeyValue <K,V> implements Serializable{//<K,V>类型参数 private K key; private V value;
public KeyValue(){} public KeyValue(K key,V value){ this.key = key; this.value = value; } @Override public String toString(){ return "[KEY]:"+key+"[VALUE]:"+value; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V v) { this.value = v; }
} //ArrayList处理方法 public static List<KeyValue<String,Integer>> handlerReList(List<KeyValue<String,Integer>> list){ Map<String,Integer> map = new HashMap<String,Integer>(); List <KeyValue<String,Integer>>returnList = new ArrayList<KeyValue<String,Integer>>(); for(KeyValue<String,Integer> key:list){ map.put(key.getKey(),key.getValue()); } Set<Map.Entry<String, Integer>> entrySet = map.entrySet(); for(Map.Entry<String, Integer> me:entrySet){ returnList.add(new KeyValue(me.getKey(),me.getValue())); } return returnList; }
javaBean里面定义,equals方法,
return this.分数=other.分数
可以放在map里,key保证是唯一的
两个javabean对象equals返回true,就认为这两个对象重复了。
当然,还要重写hashcode()方法
map是直接覆盖第一个,也就是保存的是第二个
看楼主的意思是要删除第二个,那么应该用set
遍历arraylist做判断哪些该删掉
往里存值时,map.put("物理",95);map.put("数学",100);这时map.put("物理",100);就插不进去了,三楼的方法也很好,都可以的!
代码如下:
//KeyValue类
public class KeyValue <K,V> implements Serializable{//<K,V>类型参数
private K key;
private V value;
public KeyValue(){}
public KeyValue(K key,V value){
this.key = key;
this.value = value;
}
@Override
public String toString(){
return "[KEY]:"+key+"[VALUE]:"+value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V v) {
this.value = v;
}
}
//ArrayList处理方法
public static List<KeyValue<String,Integer>> handlerReList(List<KeyValue<String,Integer>> list){
Map<String,Integer> map = new HashMap<String,Integer>();
List <KeyValue<String,Integer>>returnList = new ArrayList<KeyValue<String,Integer>>();
for(KeyValue<String,Integer> key:list){
map.put(key.getKey(),key.getValue());
}
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for(Map.Entry<String, Integer> me:entrySet){
returnList.add(new KeyValue(me.getKey(),me.getValue()));
}
return returnList;
}
如果想保留95
if(!map.containsKey("物理")){
map.put("key",value);
}
如果想保留100
直接put