快捷搜索: 王者荣耀 脱发

JAVA后台开发的瑞士军google guava实测

Google公司针对JAVA开发开源的guava工具被誉为是JAVA里面的瑞士军刀。能简化我们的代码,让我们的代码易写、易读、易于维护。而且它能提高我们的工作效率,让我们从大量重复的底层代码中脱身。由于做过很多高并发的测试,运用在项目中能大大的优化我们大部分的工作,下面说说一些常的方法。

maven项目中引入,根据自己实际的需要引入不同的版本。

<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>19.0-rc1</version> </dependency>

集合方面

//对象快速优雅的创建List<String> list = Lists.newArrayList();Map<String, String> map = Maps.newLinkedHashMap();List<String> listTemp= Lists.newArrayList("abc", "cbd");//强大的数据集合字符串拼接方法String strTemp = "1-2-3-4";List<String> list = Splitter.on("-").splitToList(strTemp);//多线程下的不变安全集合ImmutableList<String> iList = ImmutableList.of("a", "b")//map key value 重复和不可重复工具BiMap<String, String> biMapTemp = HashBiMap.create();Multimap<String, String> teachersMap = ArrayListMultimap.create();//集合交集,并集,差集HashSet setA = newHashSet(1, 2, 3);  HashSet setB = newHashSet(2, 5, 3); SetView union = Sets.union(setA, setB);SetView difference = Sets.difference(setA, setB);SetView intersection = Sets.intersection(setA, setB);//map 的交集,并集,差集HashMap<String, Integer> mapA = Maps.newHashMap();mapA.put("a", 1);mapA.put("b", 2);mapA.put("c", 3);HashMap<String, Integer> mapB = Maps.newHashMap();mapB.put("b", 20);mapB.put("c", 3);mapB.put("d", 4);MapDifference differenceMap = Maps.difference(mapA, mapB);differenceMap.areEqual();Map entriesDiffering1 = differenceMap.entriesDiffering();Map entriesOnlyLeft2 = differenceMap.entriesOnlyOnLeft();Map entriesOnlyRight3 = differenceMap.entriesOnlyOnRight();Map entriesInCommon4 = differenceMap.entriesInCommon();

字符串方面

//数组转字符串 JoinerList<String> stringSrc = Lists.newArrayList("C","Java");String resultString  = Joiner.on(",").join(stringSrc);String resultTemp = Joiner.on("-").join(listTemp);String resultTemp2 = Joiner.on(",").withKeyValueSeparator("=").join(map);//增加跳过,替换空方法skipNulls,useForNull//强大的字符串拆分方法 SplitterSplitter.on(,).trimResults().omitEmptyStrings().splitToList("foo,bar,,qux");//字符匹配器 – CharMatcher// 创建一个匹配数字字符的CharMatcher CharMatcher numMatcher = CharMatcher.inRange(0, 9);// retainFrom保留匹配到的字符(123789) System.out.println(numMatcher.retainFrom("123abc789")); String theDigits = CharMatcher.DIGIT.retainFrom(string);//只保留数字 CharMatcher.WHITESPACE.trimAndCollapseFrom(string,  );//去除空格 //字符集工StandardCharsetsbyte[] byteDis src.getBytes(StandardCharsets.UTF_8);//字符转换工具类CaseFormat,有全小写,全大写,驼峰String resultToStr = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "CONSTANT_NAME");

后续将持续增加guava下面对文件操作,缓存,并发等更多的工具介绍。

经验分享 程序员 微信小程序 职场和发展