【Guava的用法】2. collection

本文介绍了Google Guava库中的一些核心集合操作,包括创建List、Map、Set,使用Iterables.getOnlyElement()、Iterables.concat(),约束列表Constraints.constrainedList(),MultiMap和BiMap的使用,以及排序功能。特别提到了ComparisonChain和Ordering的比较功能,以及Ranges的定义和应用,如在迭代特定数字范围时的作用。
摘要由CSDN通过智能技术生成

创建List、Map

Before
Map <String, Map <Long, List <String >>> map =   new  HashMap <String, Map <Long,List <String >>>();  
 
After:(JDK7将实现该功能)
Map <String, Map <Long, List <String >>> map = Maps.newHashMap();  
 
 
 
Before:
List <String > list =   new  ArrayList <String >();  
list.add( "a" );  
list.add( "b" );  
list.add( "c" );  
list.add( "d" );  
 
After:
List <Integer > list = Lists.newArrayList( 1 ,   2 ,   3 );  

针对不可变集合:
ImmutableList <String > of = ImmutableList.of( "a" ,   "b" ,   "c" ,   "d" );  
ImmutableMap <String,String > map = ImmutableMap.of( "key1" ,   "value1" ,   "key2" ,   "value2" );  
 

Sets

HashSet setA = newHashSet( 1 ,   2 ,   3 ,   4 ,   5 );  
HashSet setB = newHashSet( 4 ,   5 ,   6 ,   7 ,   8 );  
   
SetView union = Sets.union(setA, setB);  
System.out.println( "union:" );  
for  (Integer integer : union)  
    System.out.println(integer);         
   
SetView difference = Sets.difference(setA, setB);  
System.out.println( "difference:" );  
for  (Integer integer : difference)  
    System.out.println(integer);        
   
SetView intersection = Sets.intersection(setA, setB);  
System.out.println( "intersection:" );  
for  (Integer integer : intersection)  
    System.out.println(integer);  


Maps

针对Map的用法:
MapDifference differenceMap = Maps.difference(mapA, mapB);  
  
differenceMap.areEqual();  
Map entriesDiffering = differenceMap.entriesDiffering();  
Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();  
Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();  
Map entriesInCommon = differenceMap. entriesInCommon();  
 

ImmutableList

Before:
public  Directions(Address from, Address to, List <Step > steps) {  
    this .from = from;  
    this .to = to;  
    this .steps = Collections.unmodifiableList( new  ArrayList<Step>(steps));  
}
  

After:
public  Directions(Address from, Address to, List <Step > steps) {  
    this .from = from;  
    this .to = to;  
    this .steps = ImmutableList.of(steps);  
}  
 

Iterables.getOnlyElement()

针对集合中只有一个元素的情况:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值