问题及实现
如果Admin对象的Id和Username相同 认为Admin重复, 找出adminArrayList中重复的数据,并显示重复数据在集合的序号是多少?本问题是导入Excel时如果有重复,需要报给用户哪行重复。
这个问题第一想法应该是 重写equals和hashcode方法,定义新的对象相等的方式。
@Test
public void listTest(){
ArrayList<Admin> adminArrayList = new ArrayList<>();
Admin a = new Admin();
Admin b = new Admin();
Admin c = new Admin();
Admin d = new Admin();
a.setId(1);
b.setId(3);
c.setId(3);
d.setId(1);
a.setUsername("1");
b.setUsername("3");
c.setUsername("3");
d.setUsername("1");
adminArrayList.add(a);
adminArrayList.add(b);
adminArrayList.add(c);
adminArrayList.add(d);
//如果Admin的Id和Username相同 认为Admin重复, 找出adminArrayList中重复的数据,并显示重复数据在集合的序号是多少
HashBiMap<Integer, String> map = HashBiMap.create(); // HashBiMap存储的键和值都只能唯一,不存在键与键、值与值相同的情况
for (int i = 0; i < adminArrayList.size(); i++) {
String value = adminArrayList.get(i).getUsername() + adminArrayList.get(i).getId();
if (map.containsValue(value)){
Integer indexOne = map.inverse().get(value);
System.out.println("重复数据序列号:" + indexOne.intValue() + "和" + i);
}else{
map.put(new Integer(i), value);
}
}
}
结果:
HashBiMap简介
需引入的依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
guava的优点:
工具类 就是封装平常用的方法,不需要你重复造轮子,节省开发人员时间,提高工作效率。谷歌作为大公司,当然会从日常的工作中提取中很多高效率的方法出来。所以就诞生了guava。
高效设计良好的API,被Google的开发者设计,实现和使用
遵循高效的java语法实践
使代码更刻度,简洁,简单
节约时间,资源,提高生产力
Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:
集合 [collections]
缓存 [caching]
原生类型支持 [primitives support]
并发库 [concurrency libraries]
通用注解 [common annotations]
字符串处理 [string processing]
I/O 等等。
HashBiMap简介
HashBiMap存储的键和值都只能唯一,不存在键与键、值与值相同的情况
构造方法介绍:
/** Returns a new, empty {@code HashBiMap} with the default initial capacity (16). */
public static <K, V> HashBiMap<K, V> create() {
return create(16);
}
inverse()方法:
inverse 英[ˌɪnˈvɜːs]
adj. (数量、位置)相反的,反向的; 反面; 相反的事物;
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null) ? inverse = new Inverse() : result;
}
inverse()方法实现了BiMap接口的inverse()方法
/**
* Returns the inverse view of this bimap, which maps each of this bimap's values to its
* associated key. The two bimaps are backed by the same data; any changes to one will appear in
* the other.
*
* <p><b>Note:</b>There is no guaranteed correspondence between the iteration order of a bimap and
* that of its inverse.
*
* @return the inverse view of this bimap
*/
BiMap<V, K> inverse();
具体使用:返回value的key
Integer indexOne = map.inverse().get(value);