乔人尹 - 基础编程
type: channel
link: https://underestimated.cn/tag/%E5%9F%BA%E7%A1%80%E7%BC%96%E7%A8%8B/
items: 面向guava编程（一）

面向guava编程（一）
type: item
date: 2022-05-02T14:19:00+00:00
description: guava是google开发的一个基础java类库，包括主要的模块为utilities/Functional/Collections/concurrency/cache/eventbus/work files，guava提供了很多好用的api，使用guava编程可以有效提高开发效率和代码质量。Joiner(list/map转化为string) private static final String COMMA = ","; private static final String EMPTY = ""; private static final String EQUALS = "="; public static String oldJoiner(List<String> dataList) { // 老的方法实现 if (dataList == null) { return null; } StringBuilder accum = new StringBuilder(); for (String item : dataList) { accum.append(item == null ? EMPTY : item).append(COMMA); } String joinResult = accum.toString(); return joinResult.substring(0, joinResult.length() - 1); } public static String oldJoiner(Map<String,String> dataMap){ if (dataMap == null){ return null; } // 老的方式，转换代码和判断比较多 StringBuilder accum = new StringBuilder(); for (Map.Entry<String,String> item : dataMap.entrySet()) { accum.append(item.getKey() == null ? EMPTY : item.getKey()).append(EQUALS).append(item.getValue()).append(COMMA); } String joinResult = accum.toString(); return joinResult.substring(0, joinResult.length() - 1); } public static String joiner(List<String> dataList) { if (dataList == null) { return null; } // guava的实现，该方法使用类似于python中的",".join(list) return Joiner.on(COMMA).useForNull(EMPTY).join(dataList); } public static String appendTo(List<String> dataList){ return Joiner.on(COMMA).useForNull(EMPTY).appendTo(new StringBuilder(), dataList).toString(); } public static String joiner(Map<String,String> dataMap){ if (dataMap == null){ return null; } // guava joiner将map值转化为string return Joiner.on(COMMA).useForNull(EMPTY).withKeyValueSeparator(EQUALS).join(dataMap); } public static void main(String[] args) { // 要求:将list转化为使用逗号分隔的字符串 List<String> dataList = Arrays.asList("1", "2", "3", null); System.out.println(appendTo(dataList)); // 测试代码 TestUtil.assertIsTrue(TestUtil.equals(joiner(dataList), oldJoiner(dataList)), "值不等"); dataList = null; TestUtil.assertIsTrue(TestUtil.equals(joiner(dataList), oldJoiner(dataList)), "值不等"); Map<String,String…