Guava学习笔记之Maps(1):Maps.uniqueIndex(Iterable, Function)
程序员文章站
2022-03-24 11:05:00
Guava官方文档 https://github.com/google/guava/wiki/CollectionUtilitiesExplained 官方文档这样描述: " " addresses the common case of having a bunch of objects that ......
guava官方文档 https://github.com/google/guava/wiki/collectionutilitiesexplained
官方文档这样描述:
[`maps.uniqueindex(iterable, function)`](http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/maps.html#uniqueindex-java.lang.iterable-com.google.common.base.function-) addresses the common case of having a bunch of objects that each have some unique attribute, and wanting to be able to look up those objects based on that attribute. 大概意思:描述了这样一种常见情况:有一大堆对象,每个对象都有一些独特的属性,能够根据该独特属性查找到对应对象。
demo1:
import com.google.common.collect.immutablemap; import com.google.common.collect.lists; import com.google.common.collect.maps; import java.util.arraylist; import java.util.function.function; /** * @author: lishuai * @date: 2018/12/4 10:20 * @description */ public class application { public static void main(string[] args) { // nickname属性能唯一确定一个webuser arraylist<webuser> users = lists.newarraylist(new webuser(1,"one"),new webuser(2,"two"),new webuser(1,"three"),new webuser(1,"four")); // 得到以nickname为key,webuser为值的一个map immutablemap<string, webuser> map = maps.uniqueindex(users,new com.google.common.base.function<webuser, string>() { @override public string apply(webuser user) { return user.getnickname(); } }); system.err.println("map:" + map); system.err.println("name:" + map.get("two").getnickname()); } } class webuser { private integer sid; private string nickname; public webuser(integer sid, string nickname) { this.sid = sid; this.nickname = nickname; } @override public string tostring() { return "webuser{" + "sid=" + sid + ", nickname='" + nickname + '\'' + '}'; } // set、get省略 }
可以进一步简化:
immutablemap<string, webuser> map = maps.uniqueindex(users,webuser::getnickname);
结果:
map:{one=webuser{sid=1, nickname='one'}, two=webuser{sid=2, nickname='two'}, three=webuser{sid=1, nickname='three'}, four=webuser{sid=1, nickname='four'}} name:two
demo2:
// nickname属性不能唯一确定一个webuser(有两个元素的nickname是"one") arraylist<webuser> users = lists.newarraylist(new webuser(1,"one"),new webuser(2,"one"),new webuser(1,"three"),new webuser(1,"four"));
结果:
exception in thread "main" java.lang.illegalargumentexception: multiple entries with same key: one=webuser{sid=2, nickname='one'} and one=webuser{sid=1, nickname='one'}. to index multiple values under a key, use multimaps.index.
由此可见,必须确保key的唯一性。