guava的新集合类型
Multiset占据了List和Set之间的一个灰色地带:允许重复,但是不保证顺序。
常见使用场景:Multiset有一个有用的功能,就是跟踪每种对象的数量,所以你可以用来进行数字统计
@Test
public void testMultiSet(){
HashMultiset<String> multiSet = HashMultiset.create();
multiSet.addAll(ImmutableList.of("Paul","Dean"));
multiSet.add("Paul",3);
multiSet.add("Paul");
System.out.println(multiSet);
System.out.println(multiSet.size());
System.out.println(multiSet.count("Paul"));
}
结果:
[Paul x 5, Dean]
6
5
Multimap可以很方便的实现Map<String,List<StudentDto>> 这种结构
@Test
public void testMultiMap(){
Multimap<String, User> map = ArrayListMultimap.create();
User user1 = new User("Paul",22);
User user2 = new User("Dean",33);
User user3 = new User("Lily",33);
map.put("Super",user1);
map.put("Super",user2);
map.put("Non",user3);
for (Map.Entry<String,User> entry : map.entries()) {
System.out.println("key:"+entry.getKey()+" Value:"+entry.getValue());
}
System.out.println(map.get("Super"));
System.out.println("all keys: "+map.keys());
}
BiMap提供了一种新的集合类型,它提供了key和value的双向关联的数据结构。
@Test
public void testBiMap(){
BiMap<String,Integer> map = ImmutableBiMap.of("Paul",22,"Dean",16);
//inverse方法会返回一个反转的BiMap,但是注意这个反转的map不是新的map对象,它实现了一种视图关联,这样你对于反转后的map的所有操作都会影响原先的map对象
LOGGER.info("通过BiMap反向获取key值:{}",map.inverse().get(22));
}
对map的值进行操作
@Test
public void mapTransformationValue(){
ImmutableMap<String,Integer> map = ImmutableMap.of("a",1,"b",2,"c",3);
Map<String,Integer> newMap = Maps.transformValues(map, v -> v+1);
for (String key : newMap.keySet()) {
System.out.println("key:"+key+" Value:" + newMap.get(key));
}
}
对List的值进行操作
@Test
public void listTransformationTest(){
List<String> strList = Lists.newArrayList("asd","wer","Jons","jean","Peter");
List<String> newList1 = Lists.transform(strList,s -> s.toUpperCase());
newList1.forEach(System.out::println);
strList.stream().map(String::toLowerCase).forEach(System.out::println);
}
//com.google.common.primitices包下的Ints,Doubles,Floats,Shorts,Bytes以及Bools
@Test
public void compare(){
//返回-1,0,1
int x = Ints.compare(1,2);
LOGGER.info("max : {}",x);
//包含关系
boolean y = Doubles.contains(new double[]{1,2,3},1);
LOGGER.info("Contains : {}",y);
String array = Ints.join(",",1,2,3);
LOGGER.info("join : {}" , array);
float max = Floats.max(1,2,3,4);
LOGGER.info("Max : {}",max);
}
结果:
max : -1
Contains : true
join : 1,2,3
Max : 4.0
/**
* Guava 中的String
*/
@Test
public void stringCommon(){
//判断字符串为null和空
String input = "";
boolean isNullOrEmpty = Strings.isNullOrEmpty(input);
System.out.println("input " + (isNullOrEmpty?"is":"is not") + " null or empty.");
//获取字符串相同的前缀
String a = "com.jd.coo.Hello";
String b = "com.jd.coo.Hi";
String ourCommonPrefix = Strings.commonPrefix(a,b);
System.out.println("a,b common prefix is " + ourCommonPrefix);
//获取字符串相同的后缀
String c = "com.google.Hello";
String d = "com.jd.Hello";
String ourSuffix = Strings.commonSuffix(c,d);
System.out.println("c,d common suffix is " + ourSuffix);
//补全字符串
int minLength = 4;
String padEndResult = Strings.padEnd("123", minLength, '0');
System.out.println("****************补全字符串***************");
System.out.println("padEndResult is " + padEndResult);
String padStartResult = Strings.padStart("1", 2, '0');
System.out.println("padStartResult is " + padStartResult);
}
input is null or empty.
a,b common prefix is com.jd.coo.H
c,d common suffix is .Hello
****************补全字符串***************
padEndResult is 1230
padStartResult is 01
当出现null值时,Joiner可以很好的处理
@Test
public void testGuavaJoiner(){
String[] x = {"as","sad","rt4"};
LOGGER.info("Result of Joiner : {}", Joiner.on("==").join(x));
List<String> list = Arrays.asList("123","asd",null,"fghh");
LOGGER.info("Result of Joiner except null: {}",Joiner.on(",").skipNulls().join(list));
ImmutableMap<String,Integer> map = ImmutableMap.of("1",11,"2",22,"3",33);
LOGGER.info("Result of Joiner map: {}" , Joiner.on(",").withKeyValueSeparator("=").join(map));
}
结果:
as==sad==rt4
123,asd,fghh
1=11,2=22,3=33
很好的字符串分割
/**
* Guava中的Splitter
* on():指定分隔符来分割字符串
* limit():当分割的子字符串达到了limit个时则停止分割
* fixedLength():根据长度来拆分字符串
* trimResults():去掉子串中的空格
* omitEmptyStrings():去掉空的子串
* withKeyValueSeparator():要分割的字符串中key和value间的分隔符,分割后的子串中key和value间的分隔符默认是=
*
*/
@Test
public void splitterCommon(){
ImmutableMap<String,Integer> map = ImmutableMap.of("1",11,"2",22,"3",33);
String mapString = Joiner.on(",").withKeyValueSeparator("=").join(map);
Map<String,String> map1 = Splitter.on(",").withKeyValueSeparator("=").split(mapString);
LOGGER.info("Result of Joiner map: {}" , map1);
}
//Splitter类返回的是Iterator类型的接口
@Test
public void splitterLimit(){
String str = "1#2#3#4#5#6#7";
LOGGER.info("Result of split by limit:{}",Splitter.on("#").limit(3).split(str));
String strWithSpace = "1#2##3##4###5#6";
LOGGER.info("Result of split by limit and space(doesn't deal with space):{}",Splitter.on("#").split(strWithSpace));
LOGGER.info("Result of split by limit and space:{}",Splitter.on("#").omitEmptyStrings().split(strWithSpace));
Iterable iterable = Splitter.on("#").limit(3).split(str);
Iterator iterator = iterable.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
对集合的一些排序、最大、最小值的处理
/**
* Guava的比较器Ordering
* 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):返回指定的元素作为一个列表的排序副本。
*/
@Test
public void testOrdering(){
List<String> strList = Lists.newArrayList("asd","wer","Jons","jean","Peter");
List<String> strList2 = Lists.newArrayList("asd","wer","Jons",null,"jean","Peter");
List<String> naturalSortedList = Ordering.natural().sortedCopy(strList);
List<String> naturalRecersedList = Ordering.natural().reverse().sortedCopy(strList);
List<String> nullFirstList = Ordering.natural().nullsFirst().sortedCopy(strList2);
List<String> nullLastList = Ordering.natural().nullsLast().sortedCopy(strList2);
System.out.println("naturalSortedList:"+naturalSortedList+"\nnaturalRecersedList:"+naturalRecersedList+"\nnullFirstList:"+
nullFirstList+"\nnullLastList:"+nullLastList);
List<Integer> intList = Arrays.asList(1,2,346,67,8,45,232,69);
int min = Ordering.natural().min(intList);
int max = Ordering.natural().max(intList);
System.out.println("Min:"+min+"Max: "+max);
ImmutableList<User> users = ImmutableList.of(new User("Dean",22),
new User("Xiao",33),
new User("Paul",25));
List<String> userNames = Lists.transform(users, new Function<User, String>() {
@Nullable
@Override
public String apply(@Nullable User user) {
return user.getAge() > 24 ? user.getName() : "";
}
});
Collection<String> collection = Collections2.filter(userNames,Predicates.isNull());
System.out.println("transformList:"+collection);
}
网友评论