Guava Collections
Guava Collections
山东和湖北 发表于2年前
Guava Collections
  • 发表于 2年前
  • 阅读 6
  • 收藏 0
  • 点赞 2
  • 评论 0

【腾讯云】如何购买服务器最划算?>>>   

摘要: Guava 对集合的创建 初始化 不变性 筛选 排序 以及新的集合类型

以下是练习的代码:

package guavaCollections;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.*;

import java.util.*;

/**
 * User: zhaoyun
 * Date: 16-5-12
 * Time: 上午10:00
 */
public class GuavaCollections {

    public static void main(String[] args){

        //简化集合的创建
        List<List<Map<String, String>>> list = Lists.newArrayList();
        List<String> stringList= Lists.newLinkedList();
        Set<String> stringSet= Sets.newHashSet();
        Map<String,String> stringMap= Maps.newHashMap();
        Integer[] intArrays= ObjectArrays.newArray(Integer.class, 10);

        //简化集合的初始化
        List<String> initArrayList = Lists.newArrayList("a","b","c");
        List<String> initLinkedList= Lists.newLinkedList(initArrayList);
        Set<String> initSet= Sets.newHashSet("1","2","3");
        Map<String,String> initMap= ImmutableMap.of("a","1","b","2","c","3");
        Integer[] initIntArrays= ObjectArrays.newArray(Integer.class, 10); // type 和 length

        //不变性
        ImmutableList<String> immutableList0 = ImmutableList.of("a","b","c"); //因为add 和 remove等方法已被禁止
        ImmutableSet<Integer> immutableSet0 = ImmutableSet.of(1,2,3);
        ImmutableMap<String,String> immutableMap0 = ImmutableMap.of("a","1","b","2","c","3");
        ImmutableList<String> immutableList1 = ImmutableList.copyOf(immutableList0);    //使用copy创建
        ImmutableSet immutableSet1 = ImmutableSet.copyOf(immutableSet0);
        ImmutableMap<String,String> immutableMap1 = ImmutableMap.copyOf(immutableMap0);
        ImmutableList<String> immutableList2 = ImmutableList.<String>builder().addAll(immutableList0) .add("d") .add("e").add("f").build();  //使用build创建
        ImmutableMap<String,String> immutableMap2 = ImmutableMap.<String,String>builder().put("d","4").putAll(immutableMap0).build();

        //新的集合类型
        //MultiMap     key可以重复的Map
        Multimap<String,String> multiMap = ArrayListMultimap.create();
        multiMap.put("a","b");
        multiMap.put("a","c");
        List<String> mapValues = ImmutableList.copyOf(multiMap.get("a"));

        // Table  key field value
        Table<String,String,String> table = HashBasedTable.create();
        table.put("a","b","c");

        //BiMap 映射 可以通过key找value 也可以通过value找key
        BiMap<String,Integer> biMap = HashBiMap.create();
        biMap.put("a",1);
        System.out.println(biMap.get("a"));
        System.out.println(biMap.inverse().get(1));

        //Predicate 筛选集合
        initArrayList = ImmutableList.copyOf(Collections2.filter(initArrayList,new Predicate<String>() {
            @Override
            public boolean apply( java.lang.String input) {
                return "a".equals(input);
            }
        }));


        //集合排序  简单排序

        /*Ordering
        常用静态方法
            natural():使用Comparable类型的自然顺序, 例如:整数从小到大,字符串是按字典顺序;
            usingToString() :使用toString()返回的字符串按字典顺序进行排序;
            arbitrary() :返回一个所有对象的任意顺序, 即compare(a, b) == 0 就是 a == b (identity equality)。 本身的排序是没有任何含义, 但是在VM的生命周期是一个常量。

        常用操作方法:
          reverse(): 返回与当前Ordering相反的排序:
          nullsFirst(): 返回一个将null放在non-null元素之前的Ordering,其他的和原始的Ordering一样;
          nullsLast():返回一个将null放在non-null元素之后的Ordering,其他的和原始的Ordering一样;
          compound(Comparator):返回一个使用Comparator的Ordering,Comparator作为第二排序元素,例如对bug列表进行排序,先根据bug的级别,再根据优先级进行排序;
          lexicographical():返回一个按照字典元素迭代的Ordering;
          onResultOf(Function):将function应用在各个元素上之后, 在使用原始ordering进行排序;
          greatestOf(Iterable iterable, int k):返回指定的第k个可迭代的最大的元素,按照这个从最大到最小的顺序。是不稳定的。
          leastOf(Iterable<E> iterable,int k):返回指定的第k个可迭代的最小的元素,按照这个从最小到最大的顺序。是不稳定的。
          isOrdered(Iterable):是否有序,Iterable不能少于2个元素。
          isStrictlyOrdered(Iterable):是否严格有序。请注意,Iterable不能少于两个元素。
          sortedCopy(Iterable):返回指定的元素作为一个列表的排序副本。
        */

        Ordering naturalOrdering = Ordering.natural();
        Ordering<Object> usingToStringOrdering = Ordering.usingToString();
        Ordering<Object> arbitraryOrdering = Ordering.arbitrary();

        List<Integer> orderList0 = Lists.newArrayList(7,2,4,3,5,6,1);
        List<String> orderList1 = Lists.newArrayList("c","b","a",null,"e","f");
        System.out.println("order0 :" + naturalOrdering.nullsLast().sortedCopy(orderList0));
        System.out.println("order0 desc :" +naturalOrdering.nullsLast().reverse().sortedCopy(orderList0));
        System.out.println("order1 :" + usingToStringOrdering.nullsLast().sortedCopy(orderList1));
        System.out.println("order1 desc :" + usingToStringOrdering.reverse().nullsLast().sortedCopy(orderList1));

        //对象的排序
        List<User> userList = Lists.newArrayList(new User(2L,"z","PWD2",40,new Date()),new User(1L,"b","PWD1",31,new Date()),new User(3L,"c","PWD3",1,new Date()));

        Ordering<User> userOrdering = new Ordering<User>() {
            @Override
            public int compare( User left, User right) {
                return left.getAge()-right.getAge();
            }
        };
        //根据age排序
        Ordering<User> orderingByUserName = Ordering.natural().nullsFirst().onResultOf(new Function<User,String>(){
            @Override
            public String apply( guavaCollections.User user) {
                return user.getUserName();
            }
        });
        //根据userId 排序
        Ordering<User> orderingByUserId = Ordering.natural().nullsFirst().onResultOf(new Function<User,Long>(){
            @Override
            public Long apply(User user) {
                return user.getId();
            }
        });
        //根据创建时间排序
        Ordering<User> orderingByUserDate = Ordering.natural().nullsFirst().onResultOf(new Function<User,Date>(){
            @Override
            public Date apply(User user) {
                return user.getCreateDate();
            }
        });
        //检查指定的 Iterable 根据ordering的排序规则是否有序
        boolean isOrdered = orderingByUserId.isOrdered(userList);

        //根据age排序
        userList = userOrdering.sortedCopy(userList);

        //根据ordering的排序规则,返回参数 iterable 的k个最大值。
        userList = orderingByUserId.greatestOf(userList,2);

        //两者之间比较出最小的 如果相等返回第一个元素
        User userMin = orderingByUserDate.min(new User(2L,"z","PWD2",40,new Date()),new User(1L,"b","PWD1",31,new Date()));
        //两者之间比较出最小的 如果相等返回第一个元素
        User userMax = orderingByUserName.max(new User(2L,"z","PWD2",40,new Date()),new User(1L,"b","PWD1",31,new Date()));

    }

}

User实体:

package guavaCollections;

import java.io.Serializable;
import java.util.Date;

/**
 * User: zhaoyun
 * Date: 16-5-12
 * Time: 下午1:58
 * 用户实体
 */
public class User implements Serializable{

    private static final long serialVersionUID = 8031997690938886371L;

    public User(){}
    public User(long id,String userName,String passWord,int age,Date createDate){
        this.id = id;
        this.userName = userName;
        this.passWord = passWord;
        this.age = age;
        this.createDate = createDate;
    }

    private long id;

    private String userName;

    private String passWord;

    private int age;

    private Date createDate;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

 

共有 人打赏支持
粉丝 0
博文 5
码字总数 4761
×
山东和湖北
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: