我们都知道hashmap键值是不能重复的,但在我的实际工作过程中,我需要循环一个子教学班数组,把同一个教学班下的子教学班筛选出来,以教学班Id作为主键,当我查询教学班的时候,就能根据教学班的ID查询到所有的子教学班,那么我是如何实现的呢?如下图:定义一个map
/**
* 自定义map
* 用于存取键值重复数据
* @param <K>
* @param <V>
*/
private class TempMap<K,V> {
private HashMap<K, ArrayList<V>> data = new HashMap<>();
public boolean add(K k, V v) {
// 判断是否存在key
if (data.containsKey(k)) {
data.get(k).add(v);
} else {
ArrayList<V> list = new ArrayList<>();
list.add(v); data.put(k,list);
}
return true;
}
public HashMap<K,ArrayList<V>> getData() {
return data;
}
}
// 调用
List<TeachingClassReadRangeEntity> teachingClassReadRangeEntities = redisInfoMapper.selectReadRange();
TempMap<String, TeachingClassReadRangeEntity> readRangeMap = new TempMap<>();
for(TeachingClassReadRangeEntity teachingClassReadRangeEntity : teachingClassReadRangeEntities){
readRangeMap.add(teachingClassReadRangeEntity.getTeachingClassId(), teachingClassReadRangeEntity);
}
Map<String, ArrayList<TeachingClassReadRangeEntity>> cacheReadRangeMap = new HashMap<>();
cacheReadRangeMap = readRangeMap.getData();