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的唯一性。