Google Guava 实战之Maps篇

 Guava是一种基于开源的Java库,谷歌很多项目使用它的很多核心库。这个库是为了方便编码,并减少编码错误。

 
     com.google.guava
     guava
     27.0.1-jre
 
 
     org.projectlombok
     lombok
 
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.checkerframework.checker.nullness.qual.Nullable;


import java.util.*;

/**
 * author: lucifer
 * date: 2020/5/26 15:21
 * description: TODO
 */
public class guavaMaps01 {

    public static void main(String[] args) {

        Map map1 = new HashMap<>();
        map1.put("张三", 123);
        map1.put("李四", 457);
        map1.put("王五", 235);
        map1.put("马六", 752);
        map1.put("王八", 752);

        Map map2 = new HashMap<>();
        map2.put("张三", 345);
        map2.put("马六", 752);
        map2.put("田七", 125);

        /**
         * 1、difference
         * Maps.difference(Map, Map)用来比较两个Map以获取所有不同点。该方法返回MapDifference对象
         */
        MapDifference difference = Maps.difference(map1, map2);
        //是否有差异,返回boolean
        boolean areEqual = difference.areEqual();
        System.out.println("比较两个Map是否有差异:" + areEqual);
        //两个map的交集
        Map entriesInCommon = difference.entriesInCommon();
        System.out.println("两个map都有的部分(交集)===:" + entriesInCommon);
        //键相同但是值不同值映射项。返回的Map的值类型为MapDifference.ValueDifference,以表示左右两个不同的值
        Map> entriesDiffering = difference.entriesDiffering();
        System.out.println("键相同但是值不同值映射项===:" + entriesDiffering);
        //键只存在于左边Map的映射项
        Map onlyOnLeft = difference.entriesOnlyOnLeft();
        System.out.println("键只存在于左边Map的映射项:" + onlyOnLeft);
        //键只存在于右边Map的映射项
        Map entriesOnlyOnRight = difference.entriesOnlyOnRight();
        System.out.println("键只存在于右边Map的映射项:" + entriesOnlyOnRight);
        /**
         * 2.filterEntries
         * Maps.filterEntries():过滤map
         */
        Map filterEntries = Maps.filterEntries(map1, input -> {
            if (input.getValue().equals(123) && Objects.equals(input.getKey(), "张三")) {
                return true;
            }
            return false;
        });
        System.out.println("过滤map=====filterEntries:" + filterEntries);
        /**
         * 3.filterKeys
         * Maps.filterKeys():过滤key
         */
        Map filterKeysMap = Maps.filterKeys(map1, new Predicate() {
            @Override
            public boolean apply(@Nullable String input) {
                if (input.equals("李四")) {
                    return true;
                }
                return false;
            }
        });
        System.out.println("过滤key=====filterKeys:" + filterKeysMap);
        /**
         *4.filterValues
         * Maps.filterValues():过滤value
         */
        Map filterValuesMap = Maps.filterValues(map1, new Predicate() {
            @Override
            public boolean apply(@Nullable Object input) {
                if (Objects.equals(752, input)) {
                    return true;
                }
                return false;
            }
        });
        System.out.println("过滤value=====filterValues:" + filterValuesMap);
        /**
         * 5.uniqueIndex
         * Maps.uniqueIndex():根据属性值找对象
         * 有一组对象,它们在某个属性上分别有独一无二的值,而我们希望能够按照这个属性值查找对象
         * 注:Maps.uniqueIndex():必须属性值唯一
         *否则报错:Exception in thread "main" java.lang.IllegalArgumentException: Multiple entries with same key:xxxxx. To index multiple values under a key, use Multimaps.index.
         */
        List users = new ArrayList<>();
        users.add(new User("zhangsan", 24));
        users.add(new User("lisi", 27));
        users.add(new User("wangwu", 28));
        //users.add(new User("wangwu",30));
        ImmutableMap uniqueIndex = Maps.uniqueIndex(users, new Function() {
            @Nullable
            @Override
            public Object apply(@Nullable User user) {
                return user.getUserName();
            }
        });
        System.out.println("Maps.uniqueIndex()===========uniqueIndex:" + uniqueIndex);
        /**
         * 6.index
         * Multimaps.index(): 根据属性值找对象
         * 如果您的索引可能将多个值与每个键相关联
         */
        users.add(new User("wangwu", 30));
        users.add(new User("lisi", 23));
        ImmutableListMultimap multimap = Multimaps.index(users, new Function() {
            @Nullable
            @Override
            public Object apply(@Nullable User user) {
                return user.getUserName();
            }
        });
        System.out.println("Multimaps.index()=========multimap:" + multimap);
        /**
         * 7.immutableEntry
         * Maps.immutableEntry():返回不可变的映射条目与指定的键和值
         */
        Map.Entry immutableEntry = Maps.immutableEntry("李四", 457);
        System.out.println("Maps.immutableEntry:===============immutableEntry:" + immutableEntry);
        /**
         * 8.subMap
         * Maps.subMap():返回的部分视图, map的键被包含range限制
         */
        TreeMap TreeMap = Maps.newTreeMap();
        TreeMap.put(1, "aaa");
        TreeMap.put(4, "bbb");
        TreeMap.put(2, "ccc");
        TreeMap.put(6, "ddd");
        //返回包含严格大于所有值的范围lower ,比严格小于uppe
        Range range = Range.open(0, 3);
        NavigableMap navigableMap = Maps.subMap(TreeMap, range);
        System.out.println("Maps.subMap()=================navigableMap:" + navigableMap);
        /**
         * 9.transformValues
         * Maps.transformValues:返回一个map,其中每个值都通过函数进行转换。
         */
        Map transformValues = Maps.transformValues(map1, new Function() {
            @Nullable
            @Override
            public Object apply(@Nullable Object input) {
                Integer value = Integer.valueOf(input.toString());
                return value / 2;
            }
        });
        System.out.println("Maps.transformValues===============transformValues:" + transformValues);
    }
}

@AllArgsConstructor
@Data
class User {
    private String userName;
    private Integer age;
}
 
  

 控制台打印:

比较两个Map是否有差异:false
两个map都有的部分(交集)===:{马六=752}
键相同但是值不同值映射项===:{张三=(123, 345)}
键只存在于左边Map的映射项:{李四=457, 王五=235, 王八=752}
键只存在于右边Map的映射项:{田七=125}
过滤map=====filterEntries:{张三=123}
过滤key=====filterKeys:{李四=457}
过滤value=====filterValues:{马六=752, 王八=752}
Maps.uniqueIndex()===========uniqueIndex:{zhangsan=User(userName=zhangsan, age=24), lisi=User(userName=lisi, age=27), wangwu=User(userName=wangwu, age=28)}
Multimaps.index()=========multimap:{zhangsan=[User(userName=zhangsan, age=24)], lisi=[User(userName=lisi, age=27), User(userName=lisi, age=23)], wangwu=[User(userName=wangwu, age=28), User(userName=wangwu, age=30)]}
Maps.immutableEntry:===============immutableEntry:李四=457
Maps.subMap()=================navigableMap:{1=aaa, 2=ccc}
Maps.transformValues===============transformValues:{李四=228, 张三=61, 马六=376, 王五=117, 王八=376}

 

你可能感兴趣的:(java8,guava)