当前位置:网站首页>Guava中这些Map的骚操作,让我的代码量减少了50%
Guava中这些Map的骚操作,让我的代码量减少了50%
2022-06-24 19:28:00 【InfoQ】
Map<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
Table - 双键Map
MapkeyvalueTablevaluekeyTablekeyrowKeycolumnKeyMapMap<String,Map<String,Integer>> map=new HashMap<>();
//存放元素
Map<String,Integer> workMap=new HashMap<>();
workMap.put("Jan",20);
workMap.put("Feb",28);
map.put("Hydra",workMap);
//取出元素
Integer dayCount = map.get("Hydra").get("Jan");
TableTable<String,String,Integer> table= HashBasedTable.create();
//存放元素
table.put("Hydra", "Jan", 20);
table.put("Hydra", "Feb", 28);
table.put("Trunks", "Jan", 28);
table.put("Trunks", "Feb", 16);
//取出元素
Integer dayCount = table.get("Hydra", "Feb");
Map1、获得key或value的集合
//rowKey或columnKey的集合
Set<String> rowKeys = table.rowKeySet();
Set<String> columnKeys = table.columnKeySet();
//value集合
Collection<Integer> values = table.values();
keyvalue[Hydra, Trunks]
[Jan, Feb]
[20, 28, 28, 16]
2、计算key对应的所有value的和
rowKeyvaluefor (String key : table.rowKeySet()) {
Set<Map.Entry<String, Integer>> rows = table.row(key).entrySet();
int total = 0;
for (Map.Entry<String, Integer> row : rows) {
total += row.getValue();
}
System.out.println(key + ": " + total);
}
Hydra: 48
Trunks: 44
3、转换rowKey和columnKey
TablestransposeTable<String, String, Integer> table2 = Tables.transpose(table);
Set<Table.Cell<String, String, Integer>> cells = table2.cellSet();
cells.forEach(cell->
System.out.println(cell.getRowKey()+","+cell.getColumnKey()+":"+cell.getValue())
);
cellSetrowcolumnJan,Hydra:20
Feb,Hydra:28
Jan,Trunks:28
Feb,Trunks:16
4、转为嵌套的Map
TableMapTablerowMapcolumnMapMap<String, Map<String, Integer>> rowMap = table.rowMap();
Map<String, Map<String, Integer>> columnMap = table.columnMap();
Map{Hydra={Jan=20, Feb=28}, Trunks={Jan=28, Feb=16}}
{Jan={Hydra=20, Trunks=28}, Feb={Hydra=28, Trunks=16}}
BiMap - 双向Map
MapvaluekeyforMapkeySetpublic List<String> findKey(Map<String, String> map, String val){
List<String> keys=new ArrayList<>();
for (String key : map.keySet()) {
if (map.get(key).equals(val))
keys.add(key);
}
return keys;
}
BiMapkeyvalueHashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("Hydra","Programmer");
biMap.put("Tony","IronMan");
biMap.put("Thanos","Titan");
//使用key获取value
System.out.println(biMap.get("Tony"));
BiMap<String, String> inverse = biMap.inverse();
//使用value获取key
System.out.println(inverse.get("Titan"));
IronMan
Thanos
1、反转后操作的影响
inverseBiMapBiMapBiMapBiMapHashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("Hydra","Programmer");
biMap.put("Tony","IronMan");
biMap.put("Thanos","Titan");
BiMap<String, String> inverse = biMap.inverse();
inverse.put("IronMan","Stark");
System.out.println(biMap);
BiMapBiMap{Hydra=Programmer, Thanos=Titan, Stark=IronMan}
IronManTonyStark2、value不可重复
BiMapMapMapkeyBiMapkeyvaluevalueHashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("Tony","IronMan");
biMap.put("Stark","IronMan");
IllegalArgumentException
keyvalueforcePutkeyHashBiMap<String, String> biMap = HashBiMap.create();
biMap.put("Tony","IronMan");
biMap.forcePut("Stark","IronMan");
BiMap{Stark=IronMan}
BiMapvaluevaluesSetCollectionSet<String> values = biMap.values();
Multimap - 多值Map
MapMap<String, List<Integer>> map=new HashMap<>();
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
map.put("day",list);
MultimapMapMultimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("day",1);
multimap.put("day",2);
multimap.put("day",8);
multimap.put("month",3);
Multimapkey{month=[3], day=[1, 2, 8]}
1、获取值的集合
Multimapget(key)CollectionCollection<Integer> day = multimap.get("day");
ArrayListMultimapgetListArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create();
List<Integer> day = multimap.get("day");
HashMultimapTreeMultimapMultimapMultimapgetnullList<Integer> day = multimap.get("day");
List<Integer> year = multimap.get("year");
System.out.println(day);
System.out.println(year);
[1, 2, 8]
[]
2、操作get后的集合
BiMapgetMultimapArrayListMultimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("day",1);
multimap.put("day",2);
multimap.put("day",8);
multimap.put("month",3);
List<Integer> day = multimap.get("day");
List<Integer> month = multimap.get("month");
day.remove(0);//这个0是下标
month.add(12);
System.out.println(multimap);
{month=[3, 12], day=[2, 8]}
3、转换为Map
asMapMultimapMap<K,Collection>MapMapMultimapMap<String, Collection<Integer>> map = multimap.asMap();
for (String key : map.keySet()) {
System.out.println(key+" : "+map.get(key));
}
map.get("day").add(20);
System.out.println(multimap);
month : [3]
day : [1, 2, 8]
{month=[3], day=[1, 2, 8, 20]}
4、数量问题
MultimapSystem.out.println(multimap.size());
System.out.println(multimap.entries().size());
for (Map.Entry<String, Integer> entry : multimap.entries()) {
System.out.println(entry.getKey()+","+entry.getValue());
}
4
4
month,3
day,1
day,2
day,8
size()keyvalueentries()keyvaluekeySetkeySystem.out.println(multimap.keySet().size());
MapSet<Map.Entry<String, Collection<Integer>>> entries = multimap.asMap().entrySet();
System.out.println(entries.size());
keyCollectionRangeMap - 范围Map
if-elsepublic static String getRank(int score){
if (0<=score && score<60)
return "fail";
else if (60<=score && score<=90)
return "satisfactory";
else if (90<score && score<=100)
return "excellent";
return null;
}
RangeMapRangeMapRangeMap<Integer, String> rangeMap = TreeRangeMap.create();
rangeMap.put(Range.closedOpen(0,60),"fail");
rangeMap.put(Range.closed(60,90),"satisfactory");
rangeMap.put(Range.openClosed(90,100),"excellent");
System.out.println(rangeMap.get(59));
System.out.println(rangeMap.get(60));
System.out.println(rangeMap.get(90));
System.out.println(rangeMap.get(91));
[0,60)[60,90](90,100]fail
satisfactory
satisfactory
excellent
[70,80]getnullrangeMap.remove(Range.closed(70,80));
System.out.println(rangeMap.get(75));
ClassToInstanceMap - 实例Map
ClassToInstanceMapMapClassClassputInstanceClassToInstanceMap<Object> instanceMap = MutableClassToInstanceMap.create();
User user=new User("Hydra",18);
Dept dept=new Dept("develop",200);
instanceMap.putInstance(User.class,user);
instanceMap.putInstance(Dept.class,dept);
getInstanceUser user1 = instanceMap.getInstance(User.class);
System.out.println(user==user1);
trueMap<Class,Object>Map<Class,Object> map=new HashMap<>();
User user=new User("Hydra",18);
Dept dept=new Dept("develop",200);
map.put(User.class,user);
map.put(Dept.class,dept);
ClassToInstanceMapClassToInstanceMappublic interface ClassToInstanceMap<B> extends Map<Class<? extends B>, B>{...}
valuekeyClassToInstanceMap<Map> instanceMap = MutableClassToInstanceMap.create();
HashMap<String, Object> hashMap = new HashMap<>();
TreeMap<String, Object> treeMap = new TreeMap<>();
ArrayList<Object> list = new ArrayList<>();
instanceMap.putInstance(HashMap.class,hashMap);
instanceMap.putInstance(TreeMap.class,treeMap);
HashMapTreeMapMap
ClassToInstanceMap总结
Map边栏推荐
- 【论】Deep learning in the COVID-19 epidemic: A deep model for urban traffic revitalization index
- PKI notes
- 【吴恩达笔记】机器学习基础
- Decoration home page custom full screen video playback effect GIF dynamic picture production video tutorial playback code operation settings full screen center Alibaba international station
- RFC 793 why to send reset and when to send reset
- 建木持续集成平台v2.5.0发布
- Pattern recognition - 0 introduction
- 将二维数组方阵顺时针旋转90°
- 【Camera基础(二)】摄像头驱动原理和开发&&V4L2子系统驱动架构
- Vscode netless environment rapid migration development environment (VIP collection version)
猜你喜欢

Multi view function in blender

Advanced secret of xtransfer technology newcomers: the treasure you can't miss mentor

即构「畅直播」上线!提供全链路升级的一站式直播服务

(待补充)GAMES101作业7提高-实现微表面模型你需要了解的知识

推荐模型之多任务模型:ESMM、MMOE

传输层 udp && tcp

升哲科技 AI 智能防溺水服务上线

【Camera基础(二)】摄像头驱动原理和开发&&V4L2子系统驱动架构

介绍BootLoader、PM、kernel和系统开机的总体流程

AntDB数据库在线培训开课啦!更灵活、更专业、更丰富
随机推荐
leetcode-201_2021_10_17
AntDB数据库在线培训开课啦!更灵活、更专业、更丰富
Unity关于本地坐标和世界坐标之间的转换
多路转接select
Direct attack on "three summers" production: good harvest news spreads frequently and summer broadcasting is in full swing
Remove the screen recording reminder (seven cattle cloud demo)
Introduce the overall process of bootloader, PM, kernel and system startup
SAP接口debug设置外部断点
Analysis of BBR congestion control state machine
传输层 udp && tcp
升哲科技 AI 智能防溺水服务上线
一文理解OpenStack网络
RFC 793 why to send reset and when to send reset
[Web Security Basics] some details
Multi view function in blender
WMI and PowerShell get TCP connection list
Redis+Caffeine两级缓存,让访问速度纵享丝滑
2022 international women engineers' Day: Dyson design award shows women's design strength
网络层 && IP
Ebpf XDP mount point analysis