栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

fundamentalsjavaguava

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

fundamentalsjavaguava

Guava 常用功能

guava 是 google 项目团队多年沉淀下来的工具包,在现代的分布式系统中得到广泛的应用。

基于最新版本 Guava:



	com.google.guava
	guava
	31.1-jre

文章目录
  • Guava 常用功能
    • guava.common
      • Precondition
      • CharMatcher
      • Comparators
      • Optional
      • Splitter
      • Stopwatch
    • guava.collection
      • Hash
      • BloomFilter
      • ImmutableCollections
      • Multimap
      • Multiset
      • Table
    • guava.func 函数式编程
      • Predicate
      • Functional
    • guava.cache
      • Cache

guava.common Precondition

异常判断

public static void main(String[] args) {
		
	TestPrecondition condition = new TestPrecondition();
	
	// 静态引入,
	condition = checkNotNull(condition);
	
	// 建议静态引入,提升效率import static com.google.common.base.Preconditions.checkArgument
	checkArgument(args.length == 0, "args %s missing. ", args.length);
	
	checkState(args.length == 0, "args not running");
	
	System.out.println(condition.toString());
	
}

@Override
public String toString() {
	
	// 输出 TestPrecondition{name='zs', id=1}
	return MoreObjects.toStringHelper(this)
			.add("name", name)
			.add("id", id)
			.add("petName", petName)
			// 剔除为空的属性
			.omitNullValues()
			.toString();
}
CharMatcher
public static void main(String[] args) {
		
	// CharMatcher 字符比较器,封装了常用字符比较算法
	String charMatcherResult = CharMatcher
			// 匹配字符 '0' ~ '9'
			.inRange('0', '9')
			// 或者:匹配任意字符 'a','b','c'
			.or(CharMatcher.anyOf("abc"))
			// 或者:不属于以下字符 'z' 'd' 'a' 'd' 'f'
			.or(CharMatcher.noneOf("zdadf"))
			// 或者:等于 '-'
			.or(CharMatcher.is('-'))
			// 原始字符
			.retainFrom("zdasd0dfdf-");
	
	// 结果 as0-
	System.out.println(charMatcherResult);
}
Comparators
public static void main(String[] args) {

	// JDK 原有比较器,tzId1,tzId2 是正序还是逆序?比较难于阅读
	Comparator byReverserOffsetThenName = new Comparator() {

		@Override
		public int compare(String tzId1, String tzId2) {
			int offset1 = tzId1 == null ? -1 : tzId1.indexOf("id");
			int offset2 = tzId2 == null ? -1 : tzId2.indexOf("id");
			
			int result = offset2 - offset1;
			return result == 0 ? tzId1.compareTo(tzId2) : result;
		}
	};
	
	Lists.newArrayList("aid", "ida", "idb", "bid").sort(byReverserOffsetThenName);
	
	// guava 提供 ComparisonChain 机制,代码更清晰易懂
	Ordering byReverserOffsetThenName2 = new Ordering() {

		@Override
		public int compare(String tzId1, String tzId2) {
			return ComparisonChain.start()
				.compare(tzId1 == null ? -1 : tzId1.indexOf("id"), tzId2 == null ? -1 : tzId2.indexOf("id"))
				.compare(tzId1, tzId2)
				.result();
		}
	};
	
	// Ordering 函数
	Ordering cityOrdering = Ordering.from(byReverserOffsetThenName);
	
	ArrayList list = Lists.newArrayList("aid", "ida", "idb", "bid");
	
	Lists.newArrayList("aid", "ida", "idb", "bid").sort(cityOrdering);
	
	list.sort(byReverserOffsetThenName2);
	
	list.forEach(System.out::println);

	Ordering.natural().reverse().thenComparing((a, b) -> a.toString().compareTo(b.toString()));
	
}
Optional
public static void main(String[] args) {
		
	final TestOptional obj = new TestOptional();
	
	// Optional
	Optional optional = Optional.of(obj);
	
	// 使用 or 提供为空默认值
	System.out.println(optional.or(new TestOptional()));
	
	// 使用 Optional 做数据转换
	optional.transform(c -> c.equals(obj)).get();
}
Splitter
public static void main(String[] args) {
	// Splitter
	String str = " foo, ,bar, quux,";
	
	// 字符串 Splitter
	Iterable result = Splitter.on(',')
			// 移除字符串前后空格
			.trimResults()
			// 移除为空或者为 null
			.omitEmptyStrings()
			.split(str);
	
	result.forEach(System.out::println);
	
	// 字符串 Joiner
	System.out.println(Joiner.on(", ")
			// 跳过为 null 的元素
			.skipNulls()
			.join(result));
}
Stopwatch
public static void main(String[] args) {
		
	// stopWatch 相对时间, System.nanoTime() 的替代
	Stopwatch stopWatch = Stopwatch.createStarted();
	
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	// 获得 stopWatch start() 以来经过的时间
	Duration time1 = stopWatch.elapsed();
	
	System.out.println(time1.toMillis());
	
	// 停止 stopWatch
	stopWatch.stop();
}
guava.collection Hash
public static void main(String[] args) {
		
	TestHash obj = new TestHash();
	obj.setAge(18);
	obj.setId(100000000l);
	
	// 指定对象分解为原生字段值
	Funnel petFunnel = new Funnel() {
		
		private static final long serialVersionUID = -5516438913441382127L;

		@Override
		public void funnel(Pet from, PrimitiveSink into) {
			into.putString(from.getName(), Charset.defaultCharset());
		}
	};
	
	// 为了减少 hash 冲突,解决 JDK 自带 hashCode() 长度限制为 32 位,无插件机制等问题
	HashCode hash = 
			// 支持算法切换 md5,sha1, sha256, sha512 
			// Hashing.goodFastHash(32) 让 guava 帮你选择 hash 算法
			Hashing.murmur3_128().newHasher()
			// 加入顺序不同,得到的 hash 值不同
			.putInt(obj.getAge())
			.putLong(obj.getId())
			.putObject(obj.getPet(), petFunnel)
			.hash();
	
	System.out.println(hash);
	System.out.println(hash.asInt());
	System.out.println(hash.asLong());
}
BloomFilter
public static void main(String[] args) {
		
	// 布隆过滤器
	//
	// 牺牲了正确率和时间以节省空间
	// public boolean mightContain(T);
	// true: 该元素不一定在集合中
	// false: 该元素一定不在集合中
	//
	
	// 预计大小 = 500,预计 99.99 使用率
	BloomFilter filter = BloomFilter.create(
			  Funnels.integerFunnel(),
			  500,
			  0.01);
	
	System.out.println(filter.put(50));
	System.out.println(filter.put(150));
	System.out.println(filter.put(250));
	System.out.println(filter.put(350));
	System.out.println(filter.put(450));
	System.out.println(filter.put(550));
	System.out.println(filter.put(650));
	System.out.println(filter.put(750));
	System.out.println(filter.put(850));
	System.out.println(filter.put(950));
	System.out.println(filter.mightContain(150));
	System.out.println(filter.mightContain(250));
	System.out.println(filter.mightContain(25));

	
}
ImmutableCollections
public static void main(String[] args) {
		
	// ImmutableCollection 类似 JDK 的线程安全的不可变集合
	ImmutableList list = ImmutableList.of("a", "b", "c", "d");
	
	ImmutableList list2 = ImmutableList.of("a", "b", "c", "d", "e");
	
	// 使用 copyOf 修改 ImmutableList
	list = ImmutableList.copyOf(list2);
	
	list.forEach(System.out::println);
	
	// 初始化示栗
	ImmutableSet set = ImmutableSet.builder()
			.addAll(list2)
			.add("f")
			.build();
	
	set.forEach(System.out::println);
}
Multimap
public static void main(String[] args) {
		
	// Multimap 的使用 Multimap 类似于 Java 的 Map>
	Multimap map = HashMultimap.create();
	
	map.put("a", "1");
	map.put("a", "1");
	map.put("a", "2");
	map.put("b", "2");
	
	Collection c = map.get("c");
	
	// 输出为 0
	System.out.println(c.size());
	
	// 输出为 true
	System.out.println(map.containsKey("a"));
	
	// size = 3
	System.out.println("size=" + map.size());
	
	// ListMultimap 类似于 Java 的 Map>
	ListMultimap listMultimap = ArrayListMultimap.create();
	
	listMultimap.put("a", "1");
	listMultimap.put("a", "1");
	listMultimap.put("b", "1");
	listMultimap.put("b", "2");
	
	// 输出 [1, 2]
	System.out.println(listMultimap.get("b"));

	// 输出 {a=[1, 1], b=[1, 2]}
	System.out.println(listMultimap);
	
	// k,v 都不能重复,否则会报错
	BiMap biMap = HashBiMap.create();
	biMap.put("a", "1");
	biMap.put("b", "2");
	BiMap biMap2 = biMap.inverse();
	
	// 输出 1:a n 2:b
	biMap2.forEach((k, v) -> System.out.println(k + ":" + v));
}
Multiset
public static void main(String[] args) {
		
	// 类似于 HashMap()
	Multiset multiset = HashMultiset.create();
	
	multiset.add("aa");
	multiset.add("aa");
	multiset.add("bb");
	
	// 输出 2
	System.out.println(multiset.count("aa"));
	
	// 输出 3
	System.out.println(multiset.size());
	
	// 输出 aa n bb n cc n
	Iterator iter = multiset.iterator();
	while (iter.hasNext()) {
		String str = iter.next();
		System.out.println(str);
	}
	System.out.println("-------------------");
	
	// 输出 aa n bb n
	for (String str : multiset.elementSet()) {
		System.out.println(str);
	}
}
Table
public static void main(String[] args) {
		
	// table 类似于数据库的 table 结果结构 R = 主键 ,C = 列名,V = 值
	Table table = ArrayTable.create(
			// 主键序列 1, 2, 3
			ImmutableList.of(1, 2, 3),
			// 列定义序列:'A', 'B', 'C'
			ImmutableList.of('A', 'B', 'C'));
	
	// 相当于 Map>
	
	table.put(1, 'A', "1A");
	table.put(1, 'B', "1B");
	table.put(2, 'A', "2A");
	
	// 输出为 2A
	System.out.println(table.get(2, 'A'));
	
	// 输出为 1 n 2 n 3 n
	table.rowKeySet().forEach(System.out::println);
	
	
	table.cellSet().forEach(cell -> System.out.println(cell.getRowKey() + ":" + cell.getColumnKey() + ":" + cell.getValue()));
	
	HashBasedTable hashTable = HashBasedTable.create();
	
	// 输出为 {}
	System.out.println(hashTable);
	
}
guava.func 函数式编程 Predicate
public static void main(String[] args) {
		
	// guava 函数式编程,谓词函数,返回值为 布尔 类型
	Predicate fp = new Predicate() {
		
		@Override
		public boolean apply(TestFPredicate input) {
			return true;
		}
	};
	
	// Predicate 谓词函数使用示栗
	List list = Lists.newArrayList(new TestFPredicate(), new TestFPredicate());
	
	// FluentIterable 类似于 stream
	ImmutableList resultList = FluentIterable
		.from(list)
		.filter(fp)
		.transform(Functions.toStringFunction())
		.limit(10)
		.toList();
	
	resultList.forEach(System.out::println);

	// FluentIterable 可以是哦那个 cycle 循环
	boolean allMatch = FluentIterable.from(list)
		.skip(0)
		.cycle()
		.limit(10)
		.allMatch(a -> !a.equals(new TestFPredicate()));
	
	System.out.println(allMatch);
	
}
Functional
public static void main(String[] args) {
		
	List strings = Lists.newArrayList("aa", "AA", "cc", "BB");

	// 函数式编程,获得字符串的长度
	Function lengthFunction = new Function() {

		@Override
		public Integer apply(String input) {
			return input.length();
		}
	};
	
	// 函数式编程,谓词函数,判断一个字符串是否只包含大写
	Predicate allCaps = new Predicate() {
		
		@SuppressWarnings("deprecation")
		@Override
		public boolean apply(String input) {
			return CharMatcher.javaUpperCase().matchesAllOf(input);
		}
	};
	
	// lengthFunction 和 allCaps 使用示栗 Iterables.transform
	Multiset lengths = HashMultiset.create(
			Iterables.transform(Iterables.filter(strings, allCaps), lengthFunction)
	);
	
	lengths.forEach(System.out::println);
}
guava.cache Cache
public static void main(String[] args) {
	// 
	CacheLoader loader = new CacheLoader() {

		@Override
		public String load(String key) throws Exception {
			if ("a".equals(key)) {
				return "1";
			}
			if ("b".equals(key)) {
				return "2";
			}
			return "3";
		}
	};
	
	// 初始化缓存
	LoadingCache cache = CacheBuilder.newBuilder()
			.maximumSize(2000)
			.expireAfterAccess(10, TimeUnit.SECONDS)
			.removalListener(new RemovalListener() {

				@Override
				public void onRemoval(RemovalNotification notification) {
					System.out.println("removing..." + notification.getKey());
				}
			})
			.build(loader);
	
	try {
		String value = cache.get("a");
		System.out.println(value);
	} catch (ExecutionException e) {
		e.printStackTrace();
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号