admin 管理员组文章数量: 887021
由 Google 公司开源,Guava是一种基于开源的Java库,Google Guava源于2007年的"Google Collections Library"。这个库是为了方便编码,并减少编码错误。这个库用于提供集合,缓存,支持原语句,并发性,常见注解,字符串处理,I/O和验证的实用方法。
Guava Utilites常用API
- 1. Joiner
- 2. Splitter
- 3. Preconditions
- 4. Objects
- 5. Strings
1. Joiner
String res = Joiner.on("#").join(要拼接的集合);
assertThat(res,equalTo(拼接后的结果));//跳过NUll拼接
Joiner.on("#"),skipNUlls().join(要拼接的集合);//碰到null都被替换成别的
Joiner.on("#"),useForNull("Defult").join(要拼接的集合);//返回的值和要拼接的是同一个对象
StringBuilder resultBuilder = Joiner.on("->").useForNull("*").appendTo(new StringBuilder("E"), stringListWithNullValue);//写入文档中private final String targetFileName = "D:\\Users\\Desktop\\guava\\guava-test.txt";try (FileWriter writer = new FileWriter(new File(targetFileName))) {Joiner.on("->").useForNull("*").appendTo(writer, stringListWithNullValue);assertThat(Files.isFile().test(new File(targetFileName)), equalTo(true));} catch (IOException e) {fail("append to the writer occur fetal error");}//stream流 拼接
stringListWithNullValue.stream().filter(item -> item != null && !item.isEmpty()).collect(Collectors.joining("->"));//stream流拼接使用默认替代null值
stringListWithNullValue.stream().map(item -> item == null || item.isEmpty() ? "*" : item).collect(Collectors.joining("->"));//拼接map集合
private final Map<String, String> stringMap = ImmutableMap.of("I", "am", "you", "is");
Joiner.on("->").withKeyValueSeparator("=").join(stringMap);//拼接map集合并写入txt文件
try (FileWriter writer = new FileWriter(new File(targetFileNameToMap))) {Joiner.on("->").withKeyValueSeparator("=").appendTo(writer, stringMap);assertThat(Files.isFile().test(new File(targetFileNameToMap)), equalTo(true));
} catch (IOException e) {fail("append to the writer occur fetal error");}
2. Splitter
public void testslitSplit() {List<String> result = Splitter.on("|").splitToList("A|B|C");assertThat(result, notNullValue());assertThat(result.size(), equalTo(3));assertThat(result.get(0), equalTo("A"));assertThat(result.get(1), equalTo("B"));assertThat(result.get(2), equalTo("C"));}public void testsplit_On_Split_OmitEmpty() {List<String> result = Splitter.on("|").splitToList("A|B|C||");assertThat(result, notNullValue());assertThat(result.size(), equalTo(5));//忽略空值result = Splitter.on("|").omitEmptyStrings().splitToList("A|B|C||");assertThat(result.size(), equalTo(3));}public void testsplit_On_Split_OmitEmpty_TrimResult() {List<String> result = Splitter.on("|").omitEmptyStrings().splitToList("A | B|C||");assertThat(result.size(), equalTo(3));assertThat(result.get(0), equalTo("A "));assertThat(result.get(1), equalTo(" B"));assertThat(result.get(2), equalTo("C"));//trimResults() 去掉空格result = Splitter.on("|").trimResults().omitEmptyStrings().splitToList("A | B|C||");assertThat(result.size(), equalTo(3));assertThat(result.get(0), equalTo("A"));assertThat(result.get(1), equalTo("B"));assertThat(result.get(2), equalTo("C"));}public void testsplitFixLength() {List<String> result = Splitter.fixedLength(2).splitToList("aabc");assertThat(result, notNullValue());assertThat(result.size(), equalTo(2));assertThat(result.get(0), equalTo("aa"));assertThat(result.get(1), equalTo("bc"));}public void testsplitOnSplitLimit() {List<String> result = Splitter.on("#").limit(3).splitToList("A#B#C#D");assertThat(result, notNullValue());assertThat(result.size(), equalTo(3));assertThat(result.get(0), equalTo("A"));assertThat(result.get(1), equalTo("B"));assertThat(result.get(2), equalTo("C#D"));}public void testsplitOnPatternString() {//支持正则表达式分割(传递一个字符串)List<String> result = Splitter.onPattern("\\|").trimResults().omitEmptyStrings().splitToList("A|B|C||");assertThat(result, notNullValue());assertThat(result.size(), equalTo(3));assertThat(result.get(0), equalTo("A"));assertThat(result.get(1), equalTo("B"));assertThat(result.get(2), equalTo("C"));}public void testsplitOnPattern() {//支持正则表达式分割(传递一个Pattern对象)List<String> result = Splitter.on(Pattern.compile("\\|")).trimResults().omitEmptyStrings().splitToList("A|B|C||");assertThat(result, notNullValue());assertThat(result.size(), equalTo(3));assertThat(result.get(0), equalTo("A"));assertThat(result.get(1), equalTo("B"));assertThat(result.get(2), equalTo("C"));}public void testsplitOnSplitToMap() {//分割装进Map中withKeyValueSeparator("=")Map<String,String> result = Splitter.on(Pattern.compile("\\|")).trimResults().omitEmptyStrings().withKeyValueSeparator("=").split("A=a| B=b|C=c||");assertThat(result, notNullValue());assertThat(result.size(), equalTo(3));assertThat(result.get("A"), equalTo("a"));assertThat(result.get("B"), equalTo("b"));assertThat(result.get("C"), equalTo("c"));}
3. Preconditions
//检查是否为null
Preconditions.checkNotNull(list);//检查不为null,并返回message
Preconditions.checkNotNull(list, "The list should not be null");//返回带数字的message
Preconditions.checkNotNull(list, "The list should not be null and size must be %s", 2);//判断参数类型
Preconditions.checkArgument();//判断线程状态 IllegalStateException
Preconditions.checkState();//判断索引
List<String> list = ImmutebleList.of("张三","李四");
Preconditions.checkElementIndex(10,list.size());//请求的对象不能为null
Object.requireNonNull(null);
4. Objects
import com.google.common.base.MoreObjects;
import com.google.common.collect.ComparisonChain;
import java.util.Calendar;public class ObjectsTest {static class Guava implements Comparable<Guava> {private final String manufacturer;private final String version;private final Calendar releaseDate;public Guava(String manufacturer, String version, Calendar releaseDate) {this.manufacturer = manufacturer;this.version = version;this.releaseDate = releaseDate;}@Overridepublic String toString() {return MoreObjects.toStringHelper(this).omitNullValues().add("manufacturer", this.manufacturer).add("version", this.version).add("releaseDate", this.releaseDate).toString();}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Guava guava = (Guava) o;return Objects.equals(this.manufacturer, guava.manufacturer)&& Objects.equals(this.version, guava.version)&& Objects.equals(this.releaseDate, guava.releaseDate);}@Overridepublic int hashCode() {return com.google.common.base.Objects.hashCode(manufacturer, version, releaseDate);}@Overridepublic int compareTo(Guava o) {return ComparisonChain.start().compare(this.manufacturer, o.manufacturer).compare(this.version, o.version).compare(this.releaseDate, o.releaseDate).result();}}public static void main(String[] args) {Guava guava1 = new Guava("Google", "23.0", Calendar.getInstance());System.out.println(guava1);System.out.println(guava1.hashCode());Calendar calendar = Calendar.getInstance();calendar.add(Calendar.YEAR, 1);Guava guava2 = new Guava("Google", "23.0", calendar);System.out.println(guava1.compareTo(guava2));}
}
5. Strings
@Test
public void testStringsMethods() {//将空字符串变为nullassertThat(Strings.emptyToNull(""),equalTo(null));//将null变为空字符串assertThat(Strings.nullToEmpty(null),equalTo(""));//公共前缀assertThat(Strings.commonPrefix("hahaha","hihihi"),equalTo("h"));//公共后缀assertThat(Strings.commonSuffix("hahaha","hihihi"),equalTo(""));//重复制定数量assertThat(Strings.repeat("嗨",3),equalTo("嗨嗨嗨"));//判断为空或者为nullassertThat(Strings.isNullOrEmpty(null),equalTo(true));//补充字符串到指定长度,头部填充assertThat(Strings.padStart("嗨嗨嗨",5,'嗨'),equalTo("嗨嗨嗨嗨嗨"));//补充字符到指定长度,尾部填充assertThat(Strings.padEnd("嗨嗨嗨",5,'来'),equalTo("嗨嗨嗨来来"));}@Test
public void testCharMatcher() {//匹配是否为数字类型assertThat(CharMatcher.javaDigit().matches('5'),equalTo(true));//判断字符串中包含某个字符的数量assertThat(CharMatcher.is('A').countIn("AAABBCA"),equalTo(4));//将一个或多个空格替换成*assertThat(CharMatcher.breakingWhitespace().collapseFrom(" a b c ",'*'),equalTo("*a*b*c*"));//assertThat(CharMatcher.javaDigit().or(CharMatcher.whitespace()).removeFrom("4a 1 2 3 b"),equalTo("ab"));//保留空格和数字assertThat(CharMatcher.javaDigit().or(CharMatcher.whitespace()).retainFrom("4a12 3b"),equalTo("412 3"));}
本文标签: Google
版权声明:本文标题:Google 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1687237838h79758.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论