Google Guava学习小计之集合,字符串utils

Google Guava官方教程(中文版) --加载太慢了
http://ifeve.com/google-guava/

string操作(Strings , Splitter)

/**
 * Strings和Splitter
 */
@Test
public void string() {
    //补全字符串
    int minLength = 5;
    String padEndResult = Strings.padEnd("123", minLength, '0');
    System.out.println("padEndResult is " + padEndResult);     //12300
    String padStartResult = Strings.padStart("1", 3, '0');
    System.out.println("padStartResult is " + padStartResult);   //001

    //获得两个字符串相同的前缀或者后缀
    String a = "com.jd.coo.Hello";
    String b = "com.jd.coo.Hi";
    String ourCommonPrefix = Strings.commonPrefix(a,b);
    System.out.println("a,b common prefix is " + ourCommonPrefix);  //com.jd.coo.H
   //Strings.commonSuffix(a,b) demo
    String c = "com.google.Hello";
    String d = "com.jd.Hello";
    String ourSuffix = Strings.commonSuffix(c,d);
    System.out.println("c,d common suffix is " + ourSuffix);   //.Hello

    //拆分字符串 onPattern正则
    Iterable splitResults = Splitter.onPattern("[,,]{1,}")
            .trimResults()
            .omitEmptyStrings()
            .split("hello,word,,世界,水平");

    for (String item : splitResults) {
        System.out.println(item);
    }

    //二次拆分
    String toSplitString = "a=b;c=d,e=f";
    Map kvs = Splitter.onPattern("[,;]{1,}").withKeyValueSeparator('=').split(toSplitString);
    for (Map.Entry entry : kvs.entrySet()) {
        System.out.println(String.format("%s=%s", entry.getKey(),entry.getValue())); 
    }

    //二次拆分逆向
    Map map = new HashMap();
    map.put("a", "b");
    map.put("c", "d");
    String mapJoinResult = Joiner.on(",").withKeyValueSeparator("=").join(map);
    System.out.println(mapJoinResult);  //a=b,c=d

    //合并
    String joinResult = Joiner.on(" ").join(new String[]{"hello","world"});
    System.out.println(joinResult);
}

参数的校验(Preconditions)

/**
 * Preconditions参数的校验
 * @param name
 * @param age
 * @param desc
 */
public void Preconditions(String name, int age, String desc,int state) {
    //如果为null则会抛出NullPointerException空指针异常
    Preconditions.checkNotNull(name, "name may not be null");
    //不符合条件时会抛出IllegalArgumentException异常
    Preconditions.checkArgument(age >= 18 && age < 99, "age must in range (18,99)");
    Preconditions.checkArgument(desc !=null && desc.length() < 10, "desc too long, max length is ", 10);
    //状态不正确会抛出IllegalStateException异常
    Preconditions.checkState(state==200,"state is error ",10);
 }

空指针快速失败 (Optional)

Optional.of(null);

集合增强

/**
 * 集合增强
 *     防御性编程:集合保持不变,改变抛出异常
 */
@Test
public void list() {
    //1.builder创建
    Set immutableNamedColors = ImmutableSet.builder()
            .add("red", "green","black","white","grey")
            .build();
    //immutableNamedColors.add("abc");
    for (String color : immutableNamedColors) {
        System.out.println(color);
    }

    //2.of静态方法创建
    ImmutableSet of = ImmutableSet.of("red", "green", "black", "white", "grey");

    //3.copyOf静态方法创建
    ImmutableSet.copyOf(new String[]{"red","green","black","white","grey"});

    //获得不可变集合的list
    ImmutableList strings = of.asList();
}

Multiset 元素计数

/**
 * Multiset 元素计数
 *      HashMultiset
 *      LinkedHashMultiset 即元素的排列顺序由第一次放入的顺序决定
 *      TreeMultiset
 *      EnumMultiset       元素必须是 enum 类型
 *      ImmutableMultiset  不可修改的 Mutiset
 */
@Test
public void multiset(){
    Multiset multiset = HashMultiset.create();
    String sentences = "this is a story, there is a good girl in the story.";
    Iterable words = Splitter.onPattern("[^a-z]{1,}").omitEmptyStrings().trimResults().split(sentences);
    for (String word : words) {
        multiset.add(word);
    }
    for (Object element : multiset.elementSet()) {
        System.out.println((String)element + ":" + multiset.count(element));
    }
}

BiMap 双向Map

/**
 * BiMap 双向Map
 *      HashBiMap:        key 集合与 value 集合都有 HashMap 实现
 *      EnumBiMap:        key 与 value 都必须是 enum 类型
 *      ImmutableBiMap:   不可修改的 BiMap
 */
@Test
public void biMap(){
    BiMap weekNameMap = HashBiMap.create();
    weekNameMap.put("星期一","Monday");
    weekNameMap.put("星期二","Tuesday");
    weekNameMap.put("星期三","Wednesday");
    weekNameMap.put("星期四","Thursday");
    weekNameMap.put("星期五","Friday");
    weekNameMap.put("星期六","Saturday");
    weekNameMap.put("星期日","Sunday");
    System.out.println("星期日的英文名是" + weekNameMap.get("星期日"));
    System.out.println("Sunday的中文是" + weekNameMap.inverse().get("Sunday"));
}

Multimaps:一键多值的Map

/**
 * Multimaps:一键多值的Map
 *          实现:                       Key实现:	                Value实现:
 *          ArrayListMultimap           HashMap	                ArrayList
 *          HashMultimap	            HashMap	                HashSet
 *          LinkedListMultimap	        LinkedHashMap	        LinkedList
 *          LinkedHashMultimap	        LinkedHashMap	        LinkedHashSet
 *          TreeMultimap	            TreeMap	                TreeSet
 *          ImmutableListMultimap	    ImmutableMap	        ImmutableList
 *          ImmutableSetMultimap        ImmutableMap	        ImmutableSet
 */
@Test
public void multimaps(){
    Multimap myMultimap = ArrayListMultimap.create();
    // 添加键值对
    myMultimap.put("Fruits", "Bannana");
    //给Fruits元素添加另一个元素
    myMultimap.put("Fruits", "Apple");
    myMultimap.put("Fruits", "Pear");
    myMultimap.put("Vegetables", "Carrot");
    // 获得multimap的size
    int size = myMultimap.size();
    System.out.println(size);
    // 获得Fruits对应的所有的值
    Collection fruits = myMultimap.get("Fruits");
    System.out.println(fruits);
    Collection vegetables = myMultimap.get("Vegetables");
    System.out.println(vegetables);
    //遍历Mutlimap
    for(String value : myMultimap.values()) {
        System.out.println(value);
    }// Removing a single value
    myMultimap.remove("Fruits","Pear");
    System.out.println(myMultimap.get("Fruits"));
    // Remove all values for a key
    myMultimap.removeAll("Fruits");
    System.out.println(myMultimap.get("Fruits"));
}

实现二维矩阵的数据结构

/**
 * Table: 实现二维矩阵的数据结构
 */
@Test
public void table(){
    //Integer->行, Integer->列, String->值
    Table table = HashBasedTable.create();
    for (int row = 0; row < 10; row++) {
        for (int column = 0; column < 5; column++) {
            table.put(row, column, "value of cell (" + row + "," + column + ")");
        }
    }
    for (int row=0;row rowData = table.row(row);
        for (int column =0;column < rowData.size(); column ++) {
            System.out.println("cell(" + row + "," + column + ") value is:" + rowData.get(column));
        }
    }
}

Iterators: 简化Iterator操作

/**
 * Iterators: 简化Iterator操作
 */
@Test
public void iterators(){
    List list = Lists.newArrayList("Apple","Pear","Peach","Banana");

    Predicate condition = new Predicate() {
        @Override
        public boolean apply(String input) {
            return ((String)input).startsWith("P");
        }
    };
    boolean allIsStartsWithP = Iterators.all(list.iterator(), condition);
    System.out.println("all result == " + allIsStartsWithP);

    //filter方法过滤符合条件的项
    Iterator startPElements = Iterators.filter(list.iterator(), new Predicate() {
         @Override
         public boolean apply(String input) {
             return input.startsWith("P");
         }
    });
    while (startPElements.hasNext()){
        System.out.println("filter :"+startPElements.next());
    }

    //返回符合条件的第一个元素
    String length5Element = Iterators.find(list.iterator(), new Predicate() {
         @Override
         public boolean apply(String input) {
             return input.length() == 5;
         }
    });
    System.out.println(length5Element);

    //对迭代器元素做转换
    Iterator countIterator = Iterators.transform(list.iterator(), new Function() {
         @Override
         public Integer apply(String input) {
        	 //转换为元素的长度
             return input.length();
         }
    });
    while (countIterator.hasNext()){
        System.out.println("transform :"+countIterator.next());
    }
}

转:https://www.cnblogs.com/wihainan/p/7091775.html

你可能感兴趣的:(GoogleUtils,Google,Guava学习小计之集合,字符串utils)