Java Guava工具类的使用

本文详细介绍Google的Guava工具类,涵盖集合创建与操作、文件处理、排序、时间计算等核心功能,提升Java开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Guava工具类简介

在开发中,工具类的使用避免上重复造轮子,极大的节省了开发时间,提高了工作效率,Google公司提供的Guava工具类,高效设计良好的API,遵循高效的java语法,使代码更加简洁。

使用Maven引入依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>

具体使用

1、集合的创建
// 创建普通集合
List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();

// 创建不可变集合
ImmutableList<String> list = ImmutableList.of("v1","v2");
ImmutableSet<String> set = ImmutableSet.of("v1","v2");
ImmutableMap<String, String> map = new ImmutableMap.Builder()
					.put("k1", "v1")
					.put("k2", "v2")
					.build();
// 其他不常用集合
//MultiSet: 无序+可重复count()方法获取单词的次数,增强了可读性+操作简单
 Multiset<String> mulSet = HashMultiset.create();
//Multimap: key-value,key可以重复  
Multimap<String, String> mulMap = ArrayListMultimap.create();
//BiMap: 双向Map(Bidirectional Map)键与值都不能重复
BiMap<String, String> biMap = HashBiMap.create();
//Table: 双键的Map Map--> Table-->rowKey+columnKey+value,和sql中的联合主键有点像
Table<String, String, Integer> tables = HashBasedTable.create();
2、集合的使用
// 集合转字符串 ["1","2"] => "1-2"
String result = Joiner.on("-").join(list);
// map集合转字符串 {"k1":"v1","k2","v2"} => "k1=v1,k2=v2"
String result = Joiner.on(",").withKeyValueSeparator("=").join(map);
// 字符串转为集合 "1-2" => ["1","2"]
List<String> list = Splitter.on("-").splitToList(str);
// 字符串转Map集合 "k1=v1,k2=v2" => {"k1":"v1","k2","v2"}
Map<String,String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);

// 字符串分隔时去除空格,"1  -2" => ["1","2"]
List<String> list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);
// 字符串根据多个字符分隔 "1-2,3=4" => ["1","2","3","4"]
List<String> list =  Splitter.on("-|,|=").omitEmptyStrings().trimResults().splitToList(str);

// 字符串匹配
boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches(str);
// 字符串过滤字符,只留数字  123
String numStr = CharMatcher.digit().retainFrom("abc 123 qwe");
// 字符串删除数字,只留字符 abc qwe
String str = CharMatcher.digit().removeFrom("abc 123 qwe");
3、文件操作
File file = new File("/value.txt");
List<String> list = null;
try {
    list = Files.readLines(file, Charsets.UTF_8);
} catch (Exception e) {
}

Files.copy(from,to);  //复制文件
Files.deleteDirectoryContents(File directory); //删除文件夹下的内容(包括文件与子文件夹)  
Files.deleteRecursively(File file); //删除文件或者文件夹  
Files.move(File from, File to); //移动文件
URL url = Resources.getResource("abc.xml"); //获取classpath根下的abc.xml文件url
4、Ordering排序器
natural()   对可排序类型做自然排序,如数字按大小,日期按先后排序
usingToString() 按对象的字符串形式做字典排序[lexicographical ordering]
from(Comparator)    把给定的Comparator转化为排序器
reverse()   获取语义相反的排序器
nullsFirst()    使用当前排序器,但额外把null值排到最前面。
nullsLast() 使用当前排序器,但额外把null值排到最后面。
compound(Comparator)    合成另一个比较器,以处理当前排序器中的相等情况。
lexicographical()   基于处理类型T的排序器,返回该类型的可迭代对象Iterable<T>的排序器。
onResultOf(Function)    对集合中元素调用Function,再按返回值用当前排序器排序。
Person person = new Person("aa",14);  //String name  ,Integer age
Person ps = new Person("bb",13);
Ordering<Person> byOrdering = Ordering.natural().nullsFirst().onResultOf(new Function<Person,String>(){
    public String apply(Person person){
        return person.age.toString();
    }
});
byOrdering.compare(person, ps);
System.out.println(byOrdering.compare(person, ps)); //1      person的年龄比ps大 所以输出1
5、其它操作
//计算中间代码的运行时间
Stopwatch stopwatch = Stopwatch.createStarted();
	// 业务
	// ...
long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println(nanos);

// MoreObjects 输出Person{age=11}
Person person = new Person("aa",11);
String str = MoreObjects.toStringHelper("Person").add("age", person.getAge()).toString();
System.out.println(str);  

//Set的交集、并集、差集
SetView union = Sets.union(setA, setB); 
SetView difference = Sets.difference(setA, setB); 
SetView intersection = Sets.intersection(setA, setB);
 
// 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();  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值