现在的java开发中已经有了很多的方便的工具来辅助我们开发,这里就简单讲一下guava常用的一些方法
Optional
这个在java中也有用于判断对象是否为空的
// 创建空的Optional对象
Optional.empty();
// 使用非null值创建Optional对象如果传入了一个null 会抛出空指针异常
Optional.of("aaaaa");
// 使用任意值创建Optional对象
Optional optional = Optional.ofNullable("aaaaaa");
Optional的常用方法
Optional.ofNullable(list)
.map(List::stream) // 不为空的时候做一些操作
.orElseGet(Stream::empty)//为空的时候做一些操作
.forEach(System.out::println);
//为空的时候返回 T
public T orElse(T other) {
return value != null ? value : other;
}
/**
* Return the value if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no value
* is present
* @return the value if present otherwise the result of {@code other.get()}
* @throws NullPointerException if value is not present and {@code other} is
* null
*/
//为空的时候 返回一个值
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
/**
* Return the contained value, if present, otherwise throw an exception
* to be created by the provided supplier.
*
* @apiNote A method reference to the exception constructor with an empty
* argument list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier The supplier which will return the exception to
* be thrown
* @return the present value
* @throws X if there is no value present
* @throws NullPointerException if no value is present and
* {@code exceptionSupplier} is null
*/
//为空的时候抛出异常
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
//不为空的时候转化成另一个对象
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
以上就是Optional的大致用法,了解有这个东西就可以真正想用的时候自己直接看一下源码就行了记住Optional是处理null的就行了
不可变集合 Immutable
常用的有这些,大家想用什么可以自己去找,这些不可变的集合就是创建完之后不可以在对其进行增加和删除等操作了
常用的一些使用方法
ImmutableSet.copyOf(list);
// 通过初始值,直接创建不可变集合
ImmutableSet immutableSet =
ImmutableSet.of(1, 2, 3);
// 以builder方式创建
ImmutableSet.builder()
.add(1)
.addAll(Sets.newHashSet(2, 3))
.add(4)
.build();
ImmutableMap<String, String> build = ImmutableMap.<String,String>builder().put("aa", "aa").build();
ImmutableMap<String, String> of = ImmutableMap.of("aa", "cc", "cc", "ss");
Multiset等
它是一种新的集合 他可以一两种角度去看待 一种ArrayList 另一种就是set set存的是不重复元素 list可以存重复元素
使用这个新的集合,你既可以获取不重复的所有元素也可以获取所有的元素,还可以轻松的对每个元素进行计数
常用的使用方法
HashMultiset<Character> multiset = HashMultiset.create();
char[] chars = text.toCharArray();
Chars.asList(chars).stream().forEach(p->multiset.add(p)); //添加一个元素
Set<Entry<Character>> entries =
multiset.entrySet(); //Entry 包含了这个元素和他出现的次数
Set<Character> characters = multiset.elementSet();
for(Entry<Character> entry:entries){
System.out.println(entry.getElement()+"----"+entry.getCount());
}
Set<Character> characters1 = multiset.elementSet();//返回所有不重复的元素
int a = multiset.count("a");//返回对应元素存在的次数
int size = multiset.size();//所有元素的个数
Iterator<Character> iterator = multiset.iterator(); //正常循环
while (iterator.hasNext()){
Character next = iterator.next();
}
System.out.println(multiset.count('大'));
除了HashMultiset 还有很多的具体实现大家可以自己去源码里面看一下,除了Multiset还有MultiMap等新的集合大家也可以去看一下
ArrayListMultimap<String, Integer> aa = ArrayListMultimap.create();
aa.put("aa",1);
aa.put("aa",2);
aa.put("cc",2);
List<Integer> integers = aa.get("aa");
System.out.println(JSON.toJSONString(integers));
Collection<Entry<String, Integer>> entries = aa.entries();
for(Entry<String,Integer> entry:entries){
entry.getValue();
entry.getKey();
}
Map<String, Collection<Integer>> stringCollectionMap = aa.asMap();
集合操作 Sets Lists Maps
这次只对这三个操作进行讲解,其实还有很多的集合操作如:Queues Multisets等等感兴趣的同学自己可以点开源码看一下这里就不过多讲解了,这次只讲解我们常用的一些。
Sets
他可以对set进行很多的操作:
这里就不对一些new操作进行解释大家可以自己看一下就是创建一些Set,将一些简单的操作
并集
Set<Integer> set = Sets.union(set1, set2);
System.out.println(set);
交集
Set<Integer> set = Sets.intersection(set1, set2);
System.out.println(set);
差集:如果元素属于A而且不属于B
Set<Integer> set = Sets.difference(set1, set2);
拆分所有子集合
Set<Integer> aa=new HashSet<Integer>(){{
add(1);
add(2);
add(3);
}};
Set<Set<Integer>> sets = Sets.powerSet(aa);
System.out.println(JSON.toJSONString(sets
));
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
//注意这个有限制 不能超过30个元素!!!!!!!!
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableMap<E, Integer> inputSet;
PowerSet(Set<E> input) {
checkArgument(
input.size() <= 30, "Too many elements to create power set: %s > 30", input.size());
this.inputSet = Maps.indexMap(input);
}
返回所有的可能出现的集合 (以后leetcode刷题 回溯法就用这个了 哈哈哈不知道行不行)
计算两个集合笛卡尔积
Set<List<Integer>> product =
Sets.cartesianProduct(set1, set2);
以上就是Sets的一些基本操作
Lists
同上一些新建list的操作这里不做讲解
transform 转化将一个对象list转化成另一个对象list
public static <F, T> List<T> transform(
List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<>(fromList, function)
: new TransformingSequentialList<>(fromList, function);
}
//简单例子
List<Integer> cc=new ArrayList<Integer>(){{
add(1);
add(2);
add(3);
}};
List<String> transform = Lists.transform(cc, (Integer a) -> String.valueOf(a));
拆分 partition
List<Integer> list =
Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> partition =
Lists.partition(list, 3);
字符串拆分charactersOf
ImmutableList<Character> asdcf = Lists.charactersOf("asdcf");
System.out.println(JSON.toJSONString(asdcf));
反转 reverse
List<Integer> list = Lists.newLinkedList();
list.add(1);
list.add(2);
list.add(3);
List<Integer> newList = Lists.reverse(list);
图片中最后几个方法也就是比较list,添加list,找一个元素的index,截取,这里就不做例子展示了,大家可以自己试一下
Maps
方法真的很多大家可以自己点进去看一下,我这里只介绍一些常用的吧
asMap set转化成map
Set<Integer> aaa=new HashSet<Integer>(){{
add(1);
add(2);
add(3);
}};
Map<Integer, Integer> integerIntegerMap = Maps.asMap(aaa, (Integer a) -> a + 1);
difference 两个map找不同
Map<String, Object> map1 = new HashMap<>();
map1.put("aa", 123);
map1.put("bb", 457);
map1.put("cc", 235);
map1.put("dd", 752);
map1.put("ee", 752);
Map<String, Object> map2 = new HashMap<>();
map2.put("ff", 345);
map2.put("dd", 752);
map2.put("cc", 235);
MapDifference<String, Object> difference = Maps.difference(map1, map2);
System.out.println(JSON.toJSONString(difference.entriesInCommon()));//交集
System.out.println(difference.areEqual());//是否相等
System.out.println(JSON.toJSONString(difference.entriesOnlyOnLeft()));//只有左边有
System.out.println(JSON.toJSONString(difference.entriesDiffering())); //键相同 值不同
System.out.println(JSON.toJSONString(difference.entriesOnlyOnRight())); //只有右边有
filter 过滤操作
Map<String, Object> stringObjectMap = Maps
.filterEntries(map1, (Entry<String, Object> a) -> !Objects.equals(a.getValue(), 2));
Map<String, Object> sss = Maps.filterKeys(map1, (String a) -> a.equals("sss"));
IO操作 Files
Files极大的简化了我们的io操作
CharSource charSource = Files
.asCharSource(new File("/Users/macbook/Documents/aaa.txt"), Charsets.UTF_8);
CharSink charSink = Files
.asCharSink(new File("/Users/macbook/Documents/bbb.txt"), Charsets.UTF_8);
try {
charSource.copyTo(charSink);
} catch (IOException e) {
e.printStackTrace();
}
创建一个source 创建一个sink 拷入进去就可以了很方便
布隆过滤器
BloomFilter<Integer> bloomFilter=BloomFilter.create((Integer a, PrimitiveSink primitiveSink)->primitiveSink.putInt(a),10000L,0.5);
for (int i=0;i<1000;i++){
bloomFilter.put(i);
}
System.out.println(bloomFilter.mightContain(1232454));
以上就是guava中常用到的方法,guava中还有很多的方法,感兴趣的小伙伴可以自己点开源码自己看一下。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210615181120529.jpeg#pic_center
上述如果有些的不对的。希望大家及时指正别误导了其他的小朋友 哈哈哈哈哈哈