Guava中关于字符串处理以及加强版集合的使用记录(个人学习笔记)

时间:2022-12-15 20:48:53

Guava中关于字符串的处理

  • Strings工具类的使用
// 获取共同的前缀
String commonPrefix = Strings.commonPrefix("fenglang", "fengyue");
System.out.println(commonPrefix);

// 获取共同的后缀
String commonSuffix = Strings.commonSuffix("fenglang", "fengling");
System.out.println(commonSuffix);

// 判断字符串是否为NULL或空
boolean nullOrEmpty = Strings.isNullOrEmpty("feng");
System.out.println(nullOrEmpty);

// 若字符串非空或者非null则返回字符串本身,否则返回null;
String emptyToNull = Strings.emptyToNull(null);
System.out.println(emptyToNull);

// 若字符串非空或者非null则返回字符串本身,否则返回""(空字符串)
String nullToEmpty = Strings.nullToEmpty("");
System.out.println("-->" + nullToEmpty);

// 在设定最小长度的情况下,在字符串前面增加(最小长度-原字符串长度)个字符
String padStart = Strings.padStart("feng", 6, 'g');
System.out.println(padStart);

// 在设定最小长度的情况下,在字符串后面增加(最小长度-原字符串长度)个字符
String padEnd = Strings.padEnd("feng", 8, 'g');
System.out.println(padEnd);

// 将字符串重复N次返回
String repeat = Strings.repeat("lang", 2);
System.out.println(repeat);
  • CharMatcher字符字符处理
String sequence = "java12345python678cC++Ruby!-+冯朗sdk";

// JAVA_DIGIT:匹配UNICODE数字
String retain = CharMatcher.JAVA_DIGIT.retainFrom(sequence);
System.out.println(retain);

// JAVA_LETTER:匹配字母
// JAVA_LETTER_OR_DIGET: 匹配数字或字母
// JAVA_LOWER_CASE: 匹配小写
// JAVA_UPPER_CASE: 匹配大写
// SINGLE_WIDTH:匹配单字宽字符,如中文字就是双字宽
String retain2 = CharMatcher.SINGLE_WIDTH.retainFrom(sequence);
System.out.println(retain2);

// matchesAnyOf:sequence中有任意字符能匹配Matcher,返回true
// matchesAllOf:sequence中所有字符都能匹配Matcher,返回true
// matchesNoneOf:sequence中所有字符都不能匹配Matcher,返回true
boolean matchesAnyOf = CharMatcher.is('c').matchesAnyOf(sequence);
System.out.println(matchesAnyOf);

// indexIn(CharSequence sequence):返回sequence中匹配到的第一个字符的坐标
// indexIn(CharSequence sequence,int
// start):返回从start开始,在sequence中匹配到的第一个字符的坐标
// lastIndexIn(CharSequence sequence):返回sequence中最后一次匹配到的字符的坐标
// countIn(CharSequence sequence):返回sequence中匹配到的字符计数
int indexIn = CharMatcher.anyOf("abc").indexIn(sequence);
int countIn = CharMatcher.is('a').countIn(sequence);
System.out.println(indexIn + ":" + countIn);

// removeFrom(CharSequence sequence):删除sequence中匹配到到的字符并返回
String removeFrom = CharMatcher.anyOf("abc").removeFrom(sequence);
System.out.println(removeFrom);

// retainFrom(CharSequence sequence):保留sequence中匹配到的字符并返回
String retainFrom = CharMatcher.anyOf("abc").retainFrom(sequence);
System.out.println(retainFrom);

// replaceFrom(CharSequence sequence,char
// replacement):替换sequence中匹配到的字符并返回
String replaceFrom = CharMatcher.anyOf("abc").replaceFrom(sequence, "$");
System.out.println(replaceFrom);

// trimFrom(CharSequence sequence):删除首尾匹配到的字符并返回
String trimFrom = CharMatcher.anyOf("jadk").trimFrom(sequence);
System.out.println("trim:"+trimFrom);

// trimLeadingFrom(CharSequence sequence):删除首部匹配到的字符
String trimLeadingFrom = CharMatcher.anyOf("jdk").trimLeadingFrom(sequence);
System.out.println(trimLeadingFrom);

// trimTrailingFrom(CharSequence sequence):删除尾部匹配到的字符
String trimTrailingFrom = CharMatcher.anyOf("jdk").trimTrailingFrom(sequence);
System.out.println(trimTrailingFrom);

// collapseFrom(CharSequence sequence,char
// replacement):将匹配到的组(连续匹配的字符)替换成replacement
// 注意:collapseFrom和replaceFrom的区别如下:
// replaceFrom会把匹配到的字符全部替换成replacement;
// collapseFrom则会把连续匹配到的字符替换成单个的replacement!!
// 如'a'在匹配"javaa"时,利用replaceFrom的返回值为j@v@@,而collapseFrom的返回值为j@v@;
String replace = CharMatcher.anyOf("apydk").replaceFrom(sequence, '@');
System.out.println(replace); // j@v@12345@@thon678cC++Rub@!-+冯朗s@@
String collapseFrom = CharMatcher.anyOf("apydk").collapseFrom(sequence, '@');
System.out.println(collapseFrom); // j@v@12345@thon678cC++Rub@!-+冯朗s@

//trimAndCollapseFrom(CharSequence sequence,char replacement):先trim在replace
String trimAndCollapseFrom = CharMatcher.anyOf("jadk").trimAndCollapseFrom(sequence, '#');
System.out.println(trimAndCollapseFrom);
  • Joiner拼接字符串
//skipNulls():去除null;
String join = Joiner.on("#").skipNulls().join("A",null,"B");
System.out.println(join);

//useForNull("0"):将null用别的字符进行替换
String join2=Joiner.on("#").useForNull("0").join("A",null,"B","C",null,"D");
System.out.println(join2);

StringBuilder sb=new StringBuilder();
StringBuilder appendTo = Joiner.on(";").skipNulls().appendTo(sb,"A","B","C","D");
System.out.println(sb+"-->"+appendTo);

//withKeyValueSeparator:据指定的分隔符连接 Map的 key和value
Map<String,Object> map=Maps.newHashMap();
map.put("河南","郑州");
map.put("河北","石家庄");
map.put("湖南","长沙");
map.put("湖北","武汉");
String join3 = Joiner.on(",").withKeyValueSeparator("=").join(map);
System.out.println(join3);
  • Splitter分割字符串
//omitEmptyStrings():去除结果为空的数据
//trimResults():去除分隔结果的前后空格;
//splitToList(CharSequence sequence):利用Splitter将String转化为list;
List<String> list = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(" 1,a,b, ,3,5,6");
for (String str:list) {
    System.out.println(str);
}

//withKeyValueSeparator(String separtor):使用Splitter将String转化为map;
String sequence="k1=v1;k2=v2;k3=v3;";
Map<String, String> map = Splitter.on(";").trimResults().omitEmptyStrings().withKeyValueSeparator("=").split(sequence);
for(java.util.Map.Entry<String, String> entry:map.entrySet()){
    System.out.println(entry.getKey()+":"+entry.getValue());
}

Guava中的Iterables的使用

List<String> list=Lists.newArrayList("Apple","Pear","Peach","Banana");
List<String> add=Lists.newArrayList("A","B","C","D");

//判断集合中的数据是否全部满足条件;
boolean all = Iterables.all(list,new Predicate<String>() {

    @Override
    public boolean apply(String input) {
        return input.startsWith("P");
    }
});
System.out.println(all);

//判断集合中是否存在满足条件的数据;
boolean any = Iterables.any(list,new Predicate<String>() {

    @Override
    public boolean apply(String input) {
        return input.startsWith("P");
    }
});
System.out.println(any);

//将集合进行拼接在一起
Iterable<String> concat = Iterables.concat(list,add);
Iterator<String> iterator = concat.iterator();
while(iterator.hasNext()){
    String next=iterator.next();
    System.out.println(next);
}

//contains(Iterable iterable,Object element):判断迭代器中是否包含指定元素;
boolean contains = Iterables.contains(list,"apple");
System.out.println(contains);

//从集合中过滤出符合条件的元素的集合
Iterable<String> filter = Iterables.filter(list,new Predicate<String>() {

    @Override
    public boolean apply(String input) {
        return input.length()==5;
    }
});
System.out.println(Lists.newArrayList(filter));

//从集合中找出符合条件的第一个元素并返回,若没有匹配的元素,则返回设定的默认值;
String find = Iterables.find(list,new Predicate<String>() {

    @Override
    public boolean apply(String input) {
        return input.startsWith("C");
    }
},"NONE");
System.out.println(find);

//返回某个元素在集合中的个数
int frequency = Iterables.frequency(Lists.newArrayList(1,2,1,1,2,3,1),1);
System.out.println(frequency);

//返回集合中的某一个、第一个或者最后一个元素;
String last = Iterables.getLast(list);
System.out.println(last);


//返回符合条件的集合的下标,若没有符合条件的则返回-1;
int indexOf = Iterables.indexOf(list,new Predicate<String>() {

    @Override
    public boolean apply(String input) {
        return input.startsWith("P");
    }
});
System.out.println(indexOf);

//判断集合是否为空,若为空则返回true,否则false;
boolean empty = Iterables.isEmpty(Lists.newArrayList());
System.out.println(empty);

//将集合按照size的大小分隔为(总大小/size)个集合,最后一个集合中不够的用null补齐;
Iterable<List<String>> partition = Iterables.paddedPartition(list,3);
System.out.println(partition.toString());

//将集合按照size的大小分隔为(总大小/size)个集合,若最后一个集合不够size的则只显示最后剩余的元素;
Iterable<List<String>> iterable = Iterables.partition(list,3);
System.out.println(iterable.toString());

//是否按照条件从结合中删除了某个元素,若true代表从集合中删除元素;
boolean b = Iterables.removeIf(list,new Predicate<String>() {

    @Override
    public boolean apply(String input) {
        return input.startsWith("P");
    }
});
System.out.println(b+"-->"+list.toString());

//将集合转化为数组;
String[] array = Iterables.toArray(list,String.class);
System.out.println(array.length);

//将集合中的元素进行转化;
Iterable<Integer> transform = Iterables.transform(list,new Function<String,Integer>() {

    @Override
    public Integer apply(String input) {
        return input.length();
    }
});
System.out.println(transform.toString());

//retainAll(Iterable removeFrom,Collection elementsToRetain):
//从Iterable迭代器中保留给定Collection集合中的所有元素(在迭代器中存在),其他移除!
//如果给定参数是Collection实例,则使用Collection类的retainAll()方法,否则使用Iterators.retainAll()方法!
//只要任意一个元素被保留,即可返回true,否则返回false
boolean retainAll = Iterables.retainAll(list,Lists.newArrayList("Apple","Banana","CD","Pear","Peach"));
System.out.println(retainAll+"-->"+list.toString());

Guava中的工具类Collections2的使用

List<Integer> list=Lists.newArrayList(1,2,6,8,9,3,4,5);
//filter():过滤符合条件的元素,同Iterables.filter()方法类似;
Collection<Integer> filter = Collections2.filter(list,new Predicate<Integer>() {

    @Override
    public boolean apply(Integer input) {
        return input>=3;
    }
});
System.out.println(filter.toString());

//transform():将集合中的元素进行转化,同Iterables.transform()方法类似;
Collection<String> transform = Collections2.transform(list,new Function<Integer,String>() {

    @Override
    public String apply(Integer input) {
        return (input+0.1)+"";
    }
});
System.out.println(transform.toString());

List<String> fruits=Lists.newArrayList("Banana","Peach","Apple","Pear","Orange");
//按照默认的规则进行排序,同Collections.sort(List<T> list,Comparator<? extends T> comparator)类似;
Collection<List<String>> permutations = Collections2.orderedPermutations(fruits);
System.out.println(permutations.toString());

//按照自定义的规则进行排序,//按照默认的规则进行排序,同Collections.sort(List<T> list,Comparator<? extends T> comparator)类似;
Collection<List<String>> orderedPermutations = Collections2.orderedPermutations(fruits,new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});
System.out.println(orderedPermutations);

Guava中的加强版集合的使用

  • HashMultiSet
//Multiset看似是一个Set,但实质上它继承的是Collection<E>接口,可以向Multiset中添加重复的元素,Multiset会对添加的元素做一个计数.
HashMultiset<String> set = HashMultiset.create();
set.add("A");
set.add("B");
set.add("C");
set.add("A");
set.add("C");
set.add("D");
set.add("B");
set.add("A");

//获取Set集合中的不重复的数据的总数
int size=set.entrySet().size();
System.out.println(size);

Set<String> elementSet = set.elementSet();
for(String str:elementSet){
    System.out.println(str+"-->"+set.count(str));
}

for(Entry<String> entry:set.entrySet()){
    System.out.println(entry.getElement()+"-->"+entry.getCount());
}
  • ArrayListMultimap
//Guava中的Multimap的适用场景为需要类似Map<String,Collection<String>>的数据类型.
ArrayListMultimap<String,String> create = ArrayListMultimap.create();
create.put("k1","v1");
create.put("k2","v2");
create.put("k1","v11");
create.put("k2","v22");
create.put("k1","v111");
create.put("k3","v3");
int size=create.keySet().size();
System.out.println(size);

Set<String> set = create.keySet();
for(String key:set){
    List<String> list = create.get(key);
    System.out.println(list);
}
  • HashBiMap
//BiMap也是一种Map,其特别之处在于既提供键到值的映射,也提供值到键的映射,其为双向Map.
HashBiMap<String,String> map = HashBiMap.create();
map.put("星期一","Monday");
map.put("星期二","Tuesday");
map.put("星期三","Wednesday");
map.put("星期四","Thursday");
map.put("星期五","Friday");
map.put("星期六","Saturday");
map.put("星期日","Sunday");
System.out.println(map.get("星期日"));
System.out.println(map.inverse().get("Monday"));