练习JAVA

package com.citydo.guava;

import com.google.common.base.*;
import com.google.common.base.Objects;
import com.google.common.collect.*;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentMap;

public class Guava {
    public static void main(String[] args) {
        test15();
    }
    public static  void test1(){
        StringBuilder stringBuilder = new StringBuilder("heloo");
        //字符串连接器, 以|为分割符 同时去掉null元素
        Joiner joiners=Joiner.on("|").skipNulls();
        //构成一个字符串foo|bar|baz并添加到stringbuilder
        stringBuilder=joiners.appendTo(stringBuilder,"foo","bar",null,"baz");
        System.out.println(stringBuilder);//hellofoo|bar|baz
    }

    public static  void test2(){
        FileWriter fileWriter=null;
        try {
            fileWriter=new FileWriter(new File("C:\\Users\\nick\\Desktop\\python\\tmp.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ArrayList<Date> dates = new ArrayList<>();
        dates.add(new Date());
        dates.add(null);
        dates.add(new Date());
        //构造连接器 Eugenenull元素 替换no string
        Joiner joiners=Joiner.on("#").useForNull("no string");

        try {
            //将list的元素tostring()写到fileWriter 是否覆盖取决于fileWriter的打开方式
            joiners.appendTo(fileWriter,dates);
            //必须close(),否则不会写文件
            fileWriter.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


    public static  void test3(){
        Map<Object, Object> map = Maps.newLinkedHashMap();
        map.put("Cookies","12334");
        map.put("Content-Length","300000");
        map.put("Date","2018.12.16");
        map.put("Mine","text/html");
        //用:分割键值对,并用#号分割每一个元素 返回字符串
        String join = Joiner.on("#").withKeyValueSeparator(":").join(map);
        System.out.println(join);
    }

    public static void test4(){
        //分割符为| 并去掉得到元素的前后空白
        Splitter splitter = Splitter.on("|").trimResults();
        String s = "hello | word | you | Name";
        Iterable<String> split = splitter.split(s);
        for (String it:split) {
            System.out.println(it);
        }
    }

    public static void test5(){
        Map<String, String> testMap = Maps.newLinkedHashMap();
        testMap.put("Cookies", "12332");
        testMap.put("Content-Length", "30000");
        testMap.put("Date", "2016.12.16");
        testMap.put("Mime", "text/html");
        // 用:分割键值对,并用#分割每个元素,返回字符串
        String returnedString = Joiner.on("#").withKeyValueSeparator(":").join(testMap);
        Splitter.MapSplitter ms = Splitter.on("#").withKeyValueSeparator(':');
        Map<String, String> ret = ms.split(returnedString);
        for(String it2 : ret.keySet()){
            System.out.println(it2 + " -> " + ret.get(it2));
        }

    }

    public static void test6(){
        System.out.println(Strings.isNullOrEmpty(""));//true
        System.out.println(Strings.isNullOrEmpty(null));//true
        System.out.println(Strings.isNullOrEmpty("hello"));//false
        //将null转化""
        System.out.println(Strings.nullToEmpty(null));//""
        //从尾部不断补充T只总共8个字符,如如果源字符串已经到达或者操作,则原样返回
        System.out.println(Strings.padEnd("hello",8,'T'));//helloTTT
    }

    public static void  test7(){
        Gson gs = new Gson();
        Person person = new Person();
        person.setId(1);
        person.setName("我是酱油");
        person.setAge(24);
        String objectStr = gs.toJson(person);
        //把对象转为JSON格式的字符串
        System.out.println("把对象转为JSON格式的字符串"+objectStr);

    }

    public static void test8(){
        // 空白回车换行对应换成一个#,一对一换
        String stringWithLinebreaks = "hello world\r\r\ryou are here\n\ntake it\t\t\teasy";
        String s = CharMatcher.BREAKING_WHITESPACE.replaceFrom(stringWithLinebreaks,'#');
        System.out.println(s); // hello#world###you#are#here##take#it###easy
    }


    public static void test9(){
        // 将所有连在一起的空白回车换行字符换成一个#,倒塌
        String tabString = "  hello   \n\t\tworld   you\r\nare             here  ";
        String s = CharMatcher.WHITESPACE.collapseFrom(tabString, '#');
        System.out.println(s); // #hello#world#you#are#here#

    }

    public static void test10(){
        String tabString = "hello\n\t\tworldyou\r\narehere";
        // 在前面的基础上去掉字符串的前后空白,并将空白换成一个#
        String s= CharMatcher.WHITESPACE.trimAndCollapseFrom(tabString, '#');
        System.out.println(s);// hello#world#you#are#here

    }

    public static void test11(){
     String one="1234667AS67wtd-iojasios000";
     //保留数字
     String s = CharMatcher.JAVA_DIGIT.retainFrom(one);
     System.out.println(s);
    }

    public static void test12(){
      //检查是否为null,null将抛出异常IllegalArgumentException,且第二个参数为错误消息。
      String trimRet = null;
      //String label_can_not_be_null = Preconditions.checkNotNull(trimRet, "label can not be null");
      //System.out.println(label_can_not_be_null);
      int data = 10;
      Preconditions.checkArgument(data < 100, "data must be less than 100");
    }

    public static void test13(){
        // Book用Objects的相关方法简化toString(),hashCode()的实现。
        // 用ComparisonChain简化compareTo()(Comparable接口)方法的实现。
        Book book1 = new Book();
        book1.setAuthor("Tom");
        book1.setTitle("Children King");
        book1.setIsbn("11341332443");
        System.out.println(book1);
        System.out.println(book1.hashCode());
        Book book2 = new Book();
        book2.setAuthor("Amy");
        book2.setTitle("Children King");
        book2.setIsbn("111");
        System.out.println(book2);
        System.out.println(book2.hashCode());
        System.out.println(book1.compareTo(book2));

    }

    public static void test14(){
        // 如果第一个为空,则返回第二个,同时为null,将抛出NullPointerException异常
        String someString = null;
        String value = Objects.firstNonNull(someString, "default value");
        System.out.println(value); // deafult value
    }

    public static void test15(){
        Persons person1 = new Persons("Wilma", "F",30);
        Persons person2 = new Persons("Fred",  "M",32);
        Persons person3 = new Persons("Betty", "F",32);
        Persons person4 = new Persons("Barney","M",33);
        List<Persons> personList = Lists.newArrayList(person1, person2, person3, person4);
        // 过滤年龄大于等于32的person
        Iterable<Persons> personsFilteredByAge =
                FluentIterable.from(personList).filter(new Predicate<Persons>() {
                    @Override
                    public boolean apply(Persons input) {
                        return input.getAge() > 31;
                    }
                });
        // Iterable有一个iterator方法,集合类都有一个Iterator方法
        for(Iterator<Persons> it = personsFilteredByAge.iterator(); it.hasNext();){
            System.out.println(it.next());
        }
        System.out.println(Iterables.contains(personsFilteredByAge, person2));
    }

    public static void test16(){
        Persons person1 = new Persons("Wilma", "F",30);
        Persons person2 = new Persons("Fred",  "M",32);
        Persons person3 = new Persons("Betty", "F",32);
        Persons person4 = new Persons("Barney","M",33);
        List<Persons> personList = Lists.newArrayList(person1, person2, person3, person4);
        // 将List<Person> 转化为 List<String>,数据源为personList。整体迭代。
        List<String> transformPersonList = FluentIterable.from(personList).transform(
                new Function<Persons, String>(){
                    @Override
                    public String apply(Persons person) {
                        // 不定参数,返回String类型
                        return Joiner.on("#").join(person.getName(), person.getSex(), person.getAge());
                    }
                }
        ).toList();
        for(int i = 0; i < transformPersonList.size(); i++){
            System.out.println(transformPersonList.get(i));
        }
    }

    public static void test17(){
        // s1 - s2
        Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
        Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
        // 得到第一个集合中有而第二个集合没有的字符串
        Sets.SetView res = Sets.difference(s1, s2);
        for(Iterator<String> it = res.iterator(); it.hasNext();){
            System.out.println(it.next()); // 1
        }
    }

    public static void test18(){
        // s1 - s2
        Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
        Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
        Sets.SetView res2 = Sets.symmetricDifference(s1, s2);
        for(Object it14 : res2){
            System.out.println(it14); // 1 5
        }
    }


    public static void test19(){
        // s1 - s2
        Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
        Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
        // s1和s2的交集
        Sets.SetView<String> res3 = Sets.intersection(s1, s2);
        for(String it14 : res3){
            System.out.println(it14); // 2 3 4
        }
    }


    public static void test20(){
        // s1 - s2
        Set<String> s1 = Sets.newHashSet("1", "2", "3", "4");
        Set<String> s2 = Sets.newHashSet("2", "3", "4", "5");
        Sets.SetView<String> res4 = Sets.union(s1, s2);
        for(String it14 : res4){
            System.out.println(it14); // 1 2 3 4 5
        }
    }

    public static void test21(){
        // 用ArrayList保存,一键多值,值不会被覆盖
        ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
        multimap.put("foo", "1");
        multimap.put("foo", "2");
        multimap.put("foo", "3");
        multimap.put("bar", "a");
        multimap.put("bar", "a");
        multimap.put("bar", "b");
        for(String it20 : multimap.keySet()){
            // 返回类型List<String>
            System.out.println(it20 + " : " + multimap.get(it20));
        }
        // 返回所有ArrayList的元素个数的和
        System.out.println(multimap.size());
    }

    public static  void test22(){
        // source是源的意思,封装输入流
        File writeFile = new File("/write.txt");
        try {
            // 不必打开或关闭文件流,会自动写盘
            Files.write("hello world!", writeFile, Charsets.UTF_8); // 重新写
            Files.append("你的名字", writeFile, Charsets.UTF_8); // 追加
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteSource byteSource = Files.asByteSource(writeFile);
        try {
            byte[] contents1 = byteSource.read();
            byte[] contents2 = Files.toByteArray(writeFile); // 两个方法的作用相同
            for(int i = 0; i < contents1.length; i++){
                assert(contents1[i] == contents2[i]);
                System.out.print(contents1[i] + " ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // sink是目的地的意思,封装输出流,流会自动关闭
        File tmpFile = new File("/tmp.txt"); // acd
        ByteSink byteSink = Files.asByteSink(tmpFile);
        try {
            byteSink.write(new byte[]{'a', 'c', 'd', '\n'});
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static  void test23(){
        //这里采用HashTable保存
        HashMultimap<String, String> hashMultimap = HashMultimap.create();
        hashMultimap.put("foo", "1");
        hashMultimap.put("foo", "2");
        hashMultimap.put("foo", "3");
        // 重复的键值对值保留一个
        hashMultimap.put("bar", "a");
        hashMultimap.put("bar", "a");
        hashMultimap.put("bar", "b");
        for(String it20 : hashMultimap.keySet()){
            // 返回类型List<String>
            System.out.println(it20 + " : " + hashMultimap.get(it20));
        }
        // 5
        System.out.println(hashMultimap.size());
    }

    public static void  test24(){
        // 两个键row key和column key,其实就是map中map, map<Integer, map<Integer, String> > mp
        HashBasedTable<Integer, Integer, String> table = HashBasedTable.create();
        table.put(1, 1, "book");
        table.put(1, 2, "turkey");
        table.put(2, 2, "apple");
        System.out.println(table.get(1, 1)); // book
        System.out.println(table.contains(2, 3)); // false
        System.out.println(table.containsRow(2)); // true
        table.remove(2, 2);
        System.out.println(table.get(2, 2)); // null
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.citydo</groupId>
    <artifactId>guava</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>guava</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
       <!-- 添加Guave-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <!-- 添加gson-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

猜你喜欢

转载自blog.csdn.net/qq_32447301/article/details/81363538
今日推荐