不按期更新java
初始化app
@Test public void test_init(){ Map<String,String> map = Maps.newHashMap(); }
將List轉爲Map,這個特性主要針對的場景是有一組對象,它們在某個屬性上分別有獨一無二的值,而咱們但願可以按照這個屬性值查找對象ide
List<Person> personList = Lists.newArrayList(); @Before public void before(){ for(int i=0;i<10;i++){ String temp = String.valueOf(i); Person p = new Person(Long.valueOf(i),temp,temp); personList.add(p); } } @Test public void test_list2map(){ ImmutableMap<Long,Person> map = Maps.uniqueIndex(personList, new Function<Person, Long>() { @Override public Long apply(Person input) { return input.getId(); } }); System.out.println(map); }
output:code
{0=Person{id=0, name='0', value='0'}, 1=Person{id=1, name='1', value='1'}, 2=Person{id=2, name='2', value='2'}, 3=Person{id=3, name='3', value='3'}, 4=Person{id=4, name='4', value='4'}, 5=Person{id=5, name='5', value='5'}, 6=Person{id=6, name='6', value='6'}, 7=Person{id=7, name='7', value='7'}, 8=Person{id=8, name='8', value='8'}, 9=Person{id=9, name='9', value='9'}}
將Properties轉化爲Map對象
@Test public void test_properties2map(){ Properties prop = new Properties(); prop.put("a","a1"); prop.put("b","b1"); ImmutableMap<String,String> map = Maps.fromProperties(prop); System.out.println(map); }
根據key來過濾mapget
@Test public void test_filter_by_key(){ Map<String,String> map = Maps.newHashMap(); map.put("a1","b1"); map.put("c1","d1"); map.put("c2","d2"); map.put("a2","b2"); Map<String,String> result = Maps.filterKeys(map, new Predicate<String>() { @Override public boolean apply(String input) { return input.contains("1"); } }); System.out.println(result); }
若是和java8的lambda一塊兒使用,就會更加簡潔input
@Test public void test_filter_by_key(){ Map<String,String> map = Maps.newHashMap(); map.put("a1","b1"); map.put("c1","d1"); map.put("c2","d2"); map.put("a2","b2"); Map<String,String> result = Maps.filterKeys(map,a->a.contains("1")); System.out.println(result); }
根據value來過濾mapit
@Test public void test_filter_by_value(){ Map<String,String> map = Maps.newHashMap(); map.put("a1","b1"); map.put("c1","d1"); map.put("c2","d2"); map.put("a2","b2"); System.out.println(Maps.filterValues(map,a->a.contains("1"))); }
根據key+value來過濾,其實就是Entry的方式io
@Test public void test_filter_by_entry(){ Map<String,String> map = Maps.newHashMap(); map.put("a1","b1"); map.put("c1","d1"); map.put("c2","d2"); map.put("a2","b2"); System.out.println(Maps.filterEntries(map,a->a.getKey().contains("1") && a.getValue().contains("b"))); }