guava(一)Preconditions
工具类 就是封装平常用的方法,不需要你重复造轮子,节省开发人员时间,提高工作效率。谷歌作为大公司,当然会从日常的工作中提取中很多高效率的方法出来。所以就诞生了guava。。
- 高效设计良好的API,被Google的开发者设计,实现和使用
- 遵循高效的java语法实践
- 使代码更刻度,简洁,简单
- 节约时间,资源,提高生产力
Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:
- 集合 [collections]
- 缓存 [caching]
- 原生类型支持 [primitives support]
- 并发库 [concurrency libraries]
- 通用注解 [common annotations]
- 字符串处理 [string processing]
- I/O 等等
使用
maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
一、集合
1、集合的创建与转换
普通集合的创建
List<String> list=Lists.newArrayList();
Set<String> set= Sets.newHashSet();
Map<String,String> map= Maps.newHashMap();
不变集合的创建
ImmutableList<String> ilist=ImmutableList.of("a","b");
ImmutableMap<String,String> imap=ImmutableMap.of("key1","v1","key2","v2");
ImmutableSet<String> iset=ImmutableSet.of("a","b");
当我们需要一个map中包含key为String value为List类型的时候
Multimap<String,Integer> multimap=ArrayListMultimap.create();
multimap.put("aa",1);
multimap.put("aa",2);
System.out.println(multimap.get("aa"));
将list转一定规则字符串
ImmutableList<String> ilist=ImmutableList.of("a","b");
System.out.println(Joiner.on(":").join(ilist));
将map转一定规则字符串
Map<String,String> map= Maps.newHashMap();
map.put("lanlan","11");
map.put("honghong","22");
System.out.println(Joiner.on(",").withKeyValueSeparator("==").join(map));
将string转list
String str="1-2-3-4-";
List<String> list1=Splitter.on("-").splitToList(str);
System.out.println(list1);
System.out.println(list1.size()); List<String> list2=Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);//去除空串与空格
System.out.println(list2);
System.out.println(list2.size());
将string转map
String input="xiaolan=11,honghong=22";
Map<String,String> map1=Splitter.on(",").withKeyValueSeparator("=").split(input);
System.out.println(map1);
2、集合的过滤
按照条件过滤
ImmutableList<String> ilist=ImmutableList.of("java","guava","c#","c++");
Iterable<String> fi=Iterables.filter(ilist,Predicates.or(Predicates.equalTo("java"),Predicates.equalTo("c++")));
System.out.println(fi);
自定义过滤条件
ImmutableMap<String,Integer> imap2=ImmutableMap.of("lanlan",11,"honghong",22);
Map<String,Integer> m= Maps.transformValues(imap2, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
if (integer>15){
return integer-5;
}else {
return integer;
}
}
});
System.out.println(m);
二、参数校验 Preconditions
1 .checkArgument(boolean) :
功能描述:检查boolean是否为真。 用作方法中检查参数
失败时抛出的异常类型: IllegalArgumentException
2.checkNotNull(T):
功能描述:检查value不为null, 直接返回value;
失败时抛出的异常类型:NullPointerException
3.checkState(boolean):
功能描述:检查对象的一些状态,不依赖方法参数。
失败时抛出的异常类型:IllegalStateException
4.checkElementIndex(int index, int size):
功能描述:检查index是否为在一个长度为size的list, string或array合法的范围。 index的范围区间是[0, size)。
失败时抛出的异常类型:IndexOutOfBoundsException
5.checkPositionIndex(int index, int size):
功能描述:检查位置index是否为在合法的范围。 index的范围区间是[0, size]。
失败时抛出的异常类型:IndexOutOfBoundsException
6.checkPositionIndexes(int start, int end, int size):
功能描述:检查[start, end)是一个长度为size的list, string或array合法的范围子集。0<=start<=end<=size。
失败时抛出的异常类型:IndexOutOfBoundsException
举个例子
int count=20;
//use java
if (count<20){
throw new IllegalArgumentException("must be positive : "+count);
}
//use guava
Preconditions.checkArgument(count>0,"must be positive:%s",count);
三、NULL 判断 Optional
以更优雅的方式判断非空
String s=null;
Optional<String> opt=Optional.ofNullable(s);
Optional<String> opt1=Optional.of(s); if (opt.isPresent()){
System.out.println(opt.get());
}
四、集合工具类
Iterables
1、boolean removeAll(Iterable removeFrom,Collection elementsToRemove) 从第一个集合中 移除第二个集合的所有项
2、boolean retainAll(Iterable removeFrom,Collection elementsToRetain) 从第一个集合中 移除 除第二个集合外的所有项
3、boolean removeIf(Iterable removeFrom,Predicate predicate) 从第一个集合中,移除符合条件的项
Iterables.removeIf(list, new Predicate<String>() {
// 移除集合中使得apply()方法返回为true的元素
@Override
public boolean apply(String input) {
return input.length() == 5;
}
});
4 filter 保留条件中的项
Iterable<String> ite=Iterables.filter(list,Predicates.containsPattern("a"));
5、concat 拼接多个集合
Iterable<Integer> it=Iterables.concat(Ints.asList(1,2,3),Ints.asList(4,5),Ints.asList(6));
6、frequency 查询集合中object出现的次数
Iterables.frequency(list,"aa")
7、partition 按大小分割集合
Iterable<List<String>> ii=Iterables.partition(list,2);
Iterator iterator=ii.iterator();
while (iterator.hasNext()){
List<String> li= (List<String>) iterator.next();
System.out.println(li);
}
8 getFirst(Iterable, T default) 返回iterable的第一个元素,若iterable为空则返回默认值
Iterables.getFirst(list,null));
9 getLast(Iterable) 返回iterable的最后一个元素,若iterable为空则抛出NoSuchElementException
10 elementsEqual(Iterable, Iterable) 如果两个iterable中的所有元素相等且顺序一致,返回true
11 unmodifiableIterable(Iterable) 返回iterable的不可变视图
12 limit(Iterable, int) 返回 iterable的前limit个元素集合
13 getOnlyElement(Iterable) 获取iterable中唯一的元素,如果iterable为空或有多个元素,则快速失败
14 boolean any(Iterable<T> iterable, Predicate<? super T> predicate) 是否有满足条件的元素
Iterables.any(list,Predicates.containsPattern("yy")));
15 Iterable<T> cycle(final Iterable<T> iterable) 无限循环集合
Iterable<String> ite=Iterables.cycle(list);
Iterator iterator=ite.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
16 int indexOf(Iterable<T> iterable, Predicate<? super T> predicate) 满足条件的元素第一次出现的index
int index=Iterables.indexOf(list,Predicates.containsPattern("cc"));
Collections2
1 Collection<E> filter(Collection<E> unfiltered, Predicate<? super E> predicate) 保留符合条件的元素
Collection<String> li=Collections2.filter(list,Predicates.containsPattern("a"));
for (String str:li){
System.out.println(str);
}
2 Collection<List<E>> permutations(Collection<E> elements) 求集合的排列组合
Collection<List<String>> collection = Collections2.permutations(list);
Iterator iterator1 = collection.iterator();
while (iterator1.hasNext()) {
System.out.println(iterator1.next());
}
3 Collection<List<E>> orderedPermutations(Iterable<E> elements, Comparator<? super E> comparator) 先排序,再排列组合
Collection<List<String>> collection1 = Collections2.orderedPermutations(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
Iterator iterator = collection1.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
4 <E extends Comparable<? super E>> Collection<List<E>> orderedPermutations(Iterable<E> elements) 按默认顺序排序,并排列组合
Collection<List<String>> collection1 = Collections2.orderedPermutations(list);
Iterator iterator = collection1.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
5、Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) 按条件改变集合元素的值
Collection<Integer> collection = Collections2.transform(list, new Function<String,Integer>() {
@Override
public Integer apply(String s) {
return Integer.valueOf(s);
}
});
for (Integer in:collection){
System.out.println(in);
}
Lists
1 newlist 创建各种集合
2 partition 分割集合
List<List<String>> partitions= Lists.partition(list,2);
3 asList 将数组转成集合,并增加头元素
String[] s = {"11"};
List<String> list = Lists.asList("aa", s);
4 Lists.cartesianProduct 笛卡尔积
List<List<String>> lisss = Lists.cartesianProduct(list, list1);
4 charactersOf 将字符串转不可变集合
ImmutableList<Character> immutableList=Lists.charactersOf("123456大众点评");
sets
1 newxxset 创建各种set
2 cartesianProduct 笛卡尔积
3 filter 保留选中元素
4 complementOf 给定集合的补集,枚举
EnumSet<Test> es= Sets.complementOf(collection);
enum Test {
aa, bb, cc;
}
5 difference 移除与set1相同的元素
Set<String> result=Sets.difference(set,set1);
6 intersection 交集
Set<String> result=Sets.intersection(set,set1);
7 powerSet 球组合
Set<Set<String>> result=Sets.powerSet(set1);
8 <K extends Comparable<? super K>> NavigableSet<K> subSet(NavigableSet<K> set, Range<K> range) 按range分割set
Set<String> set = Sets.newHashSet("2","1","333");
NavigableSet<String> see=Sets.newTreeSet(set);
NavigableSet<String> lala = Sets.subSet(see, Range.all());
9 symmetricDifference 球两个集合的不同元素的集合
Set<String> re=Sets.symmetricDifference(set,set1);
10 union 连接集合,并排序
Set<String> re=Sets.union(set,set1);
maps
1 new xxxmap 创建各种map
2 difference 比较两个map的不同点
MapDifference<String,String> diff= Maps.difference(map,map1);
System.out.println(diff.entriesDiffering()); //返回两个map key相同 value不同的
System.out.println(diff.entriesInCommon()); //相同的元素
System.out.println(diff.entriesOnlyOnLeft()); //只有左边集合有的key
System.out.println(diff.entriesOnlyOnRight()); //只有右边集合有的key
3 transformValues 改变value的值
Map<String, Object> result = Maps.transformValues(map, new Function<String, Object>() {
@Override
public Object apply(String input) {
if (input.equals("1")) {
return "55555";
}
return input;
}
});
4 asMap 将set转map
Map<String, String> result=Maps.asMap(set, new Function<String, String>() {
@Override
public String apply(String input) {
if (input.equals("2")){
return "22222";
}
return input;
}
});
5 fromProperties(Properties properties):通过给定的Properties实例,返回一个不可变的ImmutableMap实例
6 synchronizedBiMap(BiMap<K, V> bimap):返回一个同步的(线程安全)的bimap,由给定的bimap支持
7 unmodifiableBiMap( BiMap<? extends K, ? extends V> bimap):返回给定的bimap的不可修改的BiMap表示
8 transformEntries( Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer):返回一个map映射,其Entry为给定fromMap.Entry通过给定EntryTransformer转换后的值
9 filterKeys(Map<K, V> unfiltered, final Predicate<? super K> keyPredicate):返回给定unfilteredMap中的键值通过给定keyPredicate过滤后的map映射
10 filterValues( Map<K, V> unfiltered, final Predicate<? super V> valuePredicate):返回给定unfilteredMap中的value值通过给定keyPredicate过滤后的map映射
11 filterEntries( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate):返回给定unfilteredMap.Entry中的Entry值通过给定entryPredicate过滤后的map 映射
12 unmodifiableNavigableMap(NavigableMap<K, V> map):返回给定map的不可修改NavigableMap表示。
13 synchronizedNavigableMap( NavigableMap<K, V> navigableMap):返回一个同步的(线程安全)的NavigableMap,由给定的navigableMap支持
14 immutableEnumMap( Map<K, ? extends V> map) 转不可变集合
五 函数式编程
一个问题:为什么functions和predicates要重写equal
Functions
1 Function<Object, String> toStringFunction() 转string
Map<String, String> result = Maps.transformValues(ImmutableMap.of("a", 1, "b", 2), Functions.toStringFunction());
2 Function<T, Boolean> forPredicate(Predicate<T> predicate) 转Function<T, Boolean>
Map<String, String> map = ImmutableMap.of("a", "1", "b", "2");
Map<String, Boolean> result = Maps.transformValues(map, Functions.forPredicate(Predicates.containsPattern("a")));
3 Function<Object, E> constant(@Nullable E value) 转常量
Map<String, String> map = ImmutableMap.of("a", "1", "b", "2");
Map<String, String> result = Maps.transformValues(map, Functions.constant("sss"));
4 Function<K, V> forMap(Map<K, V> map 以map的映射方式为funtion
Map<String, String> map = ImmutableMap.of("a", "1", "b", "2");
Map<String, Integer> result = Maps.transformValues(map, Functions.forMap(ImmutableMap.of("1",1,"2",222)));
5 compose(Function<B, C> g, Function<A, ? extends B> f) 组合两个function,计算顺序是从后到前
Map<String, Integer> map = ImmutableMap.of("a", 1, "b", 2);
Map<String, String> result = Maps.transformValues(map, Functions.compose(Functions.constant("la"),Functions.toStringFunction()));
Predicates
1 Predicate<T> equalTo(@Nullable T target) 比较相等
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("a", 1, "b", 2),Predicates.equalTo("a"));
2 Predicate<CharSequence> containsPattern(String pattern) 是否包含
Map<String, Integer> map = ImmutableMap.of("a", 1, "b", 2);
Map<String, Integer> result = Maps.filterKeys(map,Predicates.containsPattern("a"));
3 Predicate<CharSequence> contains(Pattern pattern) 是否匹配正则
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("a", 1, "b", 2),Predicates.contains(Pattern.compile("a")));
4 Predicate<T> or(Predicate<? super T> first, Predicate<? super T> second) |
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("a", 1, "b", 2),Predicates.or(Predicates.equalTo("aa"),Predicates.containsPattern("a")));
5 Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) &
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("a", 1, "b", 2),Predicates.and(Predicates.equalTo("aa"),Predicates.containsPattern("a")));
6 Predicate<T> in(Collection<? extends T> target) in
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("aa", 1, "ab", 2),Predicates.in(ImmutableList.of("aa")));
7 Predicate<Object> instanceOf(Class<?> clazz) 是否继承自某种类型
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("aa", 1, "ab", 2),Predicates.instanceOf(String.class));
8 Predicate<T> not(Predicate<T> predicate) 取反
Map<String, Integer> result = Maps.filterKeys(ImmutableMap.of("aa", 1, "ab", 2),Predicates.not(Predicates.containsPattern("aa")));
9 Predicate<T> notNull()
10 Predicate<T> isNull()
11 Predicate<T> alwaysFalse()
12 Predicate<T> alwaysTrue()
FluentIterable
举个例子
FluentIterable<String> fluentIterable = FluentIterable.from(ImmutableList.of("233")).filter(Predicates.containsPattern("2"))
.filter(Predicates.containsPattern("3"));
六 比较器
Ordering
Ordering中有4种静态方法用于创建Ordering排序器
1 Ordering<Object> arbitrary() 任意顺序比较器
List<String> result= Ordering.arbitrary().sortedCopy(ImmutableList.of("33","11","22"));
2 <C extends Comparable> Ordering<C> natural() 自然顺序
List<String> result= Ordering.natural().sortedCopy(ImmutableList.of("33","11","22"));
3 Ordering<Object> usingToString() 以转成string后比较
List<Integer> result= Ordering.usingToString().sortedCopy(Ints.asList(2,3));
4 Ordering<T> from(Comparator<T> comparator) Comparator转Ordering
List<Integer> result = Ordering.from(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
}).sortedCopy(Ints.asList(3, 2));
根据上面的方法创建Ordering后,可以继续调用如下方法创建组合功能的排序器:
1 Ordering<S> reverse() 获取语义相反的排序器
Ordering or = Ordering.natural().reverse();
2 Ordering<S> nullsFirst() 将null元素放在前面
Ordering or = Ordering.natural().nullsFirst();
3 Ordering<S> nullsLast() 将null元素放在后面
Ordering or = Ordering.natural().nullsLast();
4 Ordering<U> compound(Comparator<? super U> secondaryComparator) 合成另一个比较器,以处理排序中相等的元素
Ordering or = Ordering.natural().compound(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return 0;
}
});
5 onResultOf(Function<F, ? extends T> function) 先调用function,再按排序器排序
Ordering or = Ordering.natural().onResultOf(new Function<String, String>() {
@Override
public String apply(String input) {
return null;
}
});
创建完Ordering排序器后,即可使用它对集合或元素进行操作
1 List<E> greatestOf(Iterable<E> iterable, int k) 最大的k个元素
List<String> lis=Ordering.natural().greatestOf(ImmutableList.of("a","b","c","d"),2);
2 boolean isOrdered(Iterable<? extends T> iterable) 是否已按迭代器排序,允许有相等元素
boolean ordered=Ordering.natural().isOrdered(ImmutableList.of("a","b","c","d"));
3 boolean isStrictlyOrdered(Iterable<? extends T> iterable) 是否严格排序,不允许有相等元素
boolean ordered=Ordering.natural().isStrictlyOrdered(ImmutableList.of("a","b","b","d"));
4 List<E> sortedCopy(Iterable<E> elements) 排序
List<String> li =Ordering.natural().sortedCopy(ImmutableList.of("e","b","c","d"));
5 E max(@Nullable E a, @Nullable E b)
String li =Ordering.natural().max("a","b");
5 E min(@Nullable E a, @Nullable E b)
String li =Ordering.natural().min("a","b");
guava(一)Preconditions的更多相关文章
- guava学习--Preconditions
转载:https://my.oschina.net/realfighter/blog/349819 Preconditions是guava提供的用于进行代码校验的工具类,其中提供了许多重要的静态校验方 ...
- 【Guava】PreConditions来校验参数
前置条件:让方法调用的前置条件判断更简单. 在我们的日常开发中,经常要对入参进行一定的参数校验,比如是否为空,参数的取值范围是否符合要求等等.这种参数校验如果我们单独进行校验的话,代码的重复率比较高, ...
- Guava学习笔记(2):Preconditions优雅的检验参数
转自:http://www.cnblogs.com/peida/p/Guava_Preconditions.html 在日常开发中,我们经常会对方法的输入参数做一些数据格式上的验证,以便保证方法能够按 ...
- Guava学习笔记:Preconditions优雅的检验参数
在日常开发中,我们经常会对方法的输入参数做一些数据格式上的验证,以便保证方法能够按照正常流程执行下去.对于可预知的一些数据上的错误,我们一定要做事前检测和判断,来避免程序流程出错,而不是完全通过错误处 ...
- Guava API学习之Preconditions优雅的检验参数 编辑
在日常开发中,我们经常会对方法的输入参数做一些数据格式上的验证,以便保证方法能够按照正常流程执行下去.对于可预知的一些数据上的错误,我们一定要做 事前检测和判断,来避免程序流程出错,而不是完全通过错误 ...
- Guava Preconditions 工具参数前置校验
guava 提供 Preconditions 作为代码校验的工具类,用来简化开发中对代码的校验或预处理,在逻辑开始前进行合理性校验,避免参数传入过深导致的数据错误. 并且能够在不符合校验条件的地方, ...
- Guava学习笔记:Preconditions优雅的检验参数(java)
http://www.cnblogs.com/peida/p/guava_preconditions.html 在日常开发中,我们经常会对方法的输入参数做一些数据格式上的验证,以便保证方法能够按照正常 ...
- Guava:好用的java类库 学习小记
基础功能 google guava中定义的String操作 在google guava中为字符串操作提供了很大的便利,有老牌的判断字符串是否为空字符串或者为null,用指定字符填充字符串,以及拆分合并 ...
- Google Guava新手教程
以下资料整理自网络 一.Google Guava入门介绍 引言 Guavaproject包括了若干被Google的 Java项目广泛依赖 的核心库,比如:集合 [collections] . ...
- Google Guava中的前置条件
前置条件:让方法调用的前置条件判断更简单. Guava在Preconditions类中提供了若干前置条件判断的实用方法,我们建议[在Eclipse中静态导入这些方法]每个方法都有三个变种: check ...
随机推荐
- fatal error compiling: tools.jar not found
在Eclipse中使用Maven提供的Install(打包)命令插件的时候报错[Fatal error compiling: tools.jar not found]. 报错的原因 报错的原因从错误信 ...
- 【UOJ#62】【UR #5】怎样跑得更快(莫比乌斯反演)
[UOJ#62][UR #5]怎样跑得更快(莫比乌斯反演) 题面 UOJ 题解 众所周知,\(lcm(i,j)=\frac{ij}{gcd(i,j)}\),于是原式就变成了: \[\sum_{j=1} ...
- 使用SolrJ(即java客户端)开发Solr。
1.什么是SolrJ呢? 答:Solrj是访问Solr服务的java客户端,提供索引和搜索的请求方法,SolrJ通常在嵌入在业务系统中,通过SolrJ的API接口操作Solr服务.开始配置schema ...
- 【C#夯实】我与接口二三事:IEnumerable、IQueryable 与 LINQ
序 学生时期,有过小组作业,当时分工一人做那么两三个页面,然而在前端差不多的时候,我和另一个同学发生了争执.当时用的是简单的三层架构(DLL.BLL.UI),我个人觉得各写各的吧,到时候合并,而他觉得 ...
- css样式篇
list-style list-style-type 设置列表项标记的类型 list-style-position 可设置outside(列表项目标记放置在文本以内,且环绕文本根据标记对齐) ...
- AES加解密异常java.security.InvalidKeyException: Illegal key size
AES加解密异常 Java后台AES解密,抛出异常如下:java.security.InvalidKeyException: Illegal key size Illegal key size or ...
- Android Studio 3.5+ 使用androidx的recyclerView
一 File->project structure->Dependencies: 点击All Dependencies处的加号,选择Library Dependency: 在step1处输 ...
- 014.统一建模语言UML
1.UML 的设计目的 UML是为了简化和强化现有的大量面向对象开发方法这一目的而开发的. UML 适用于各种软件开发方法.软件生命周期的各个阶段.各种应用领域以及各种开发工具,是一种总结了以往建模技 ...
- 数据库-mysql01 简单介绍以及安装部署
本次mysql数据库安装采用二进制安装(免安装即绿色版),数据库版本是mysql5.7.26 首先下载mysql安装包,然后上传服务器里,最后解压. 卸载centos7自带的数据库软件包: [root ...
- 【洛谷P4542】 [ZJOI2011]营救皮卡丘(费用流)
洛谷 题意: 给出\(n\)个点,\(m\)条边,现在有\(k,k\leq 10\)个人从\(0\)号点出发前往\(n\)点. 规定若某个人想要到达\(x\)点,则\(1\)~\(x-1\)号点都有人 ...