Google Guava - 字符串处理

Posted s-star

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Google Guava - 字符串处理相关的知识,希望对你有一定的参考价值。

# (一)连接器[Joiner]

package com.jcx.guava.utilites;

import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.junit.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.ImmutableMap.of;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class JoinerTest {

    private final List<String> stringList = Arrays.asList(
            "beijing", "shanghai", "guangzhou", "shenzhen", "hangzhou"
    );

    private final List<String> stringListWithNull = Arrays.asList(
            "beijing", "shanghai", "guangzhou", "shenzhen", null
    );

    private final Map<String, String> stringMap = of("beijing", "shanghai", "guangzhou", "shenzhen");

    private final String targetFileName = "E:\txt\guava-joiner.txt";
    private final String targetFileNameToMap = "E:\txt\guava-joiner-map.txt";

    @Test
    public void testJoinOnJoin() {
        String result = Joiner.on("#").join(stringList);
        assertThat(result, equalTo("beijing#shanghai#guangzhou#shenzhen#hangzhou"));
    }

    @Test(expected = NullPointerException.class)
    public void testJoinOnJoinWithNull() {
        String result = Joiner.on("#").join(stringListWithNull);
        assertThat(result, equalTo("beijing#shanghai#guangzhou#shenzhen"));
    }

    @Test
    public void testJoinOnJoinWithNullButSkip() {
        String result = Joiner.on("#").skipNulls().join(stringListWithNull);
        assertThat(result, equalTo("beijing#shanghai#guangzhou#shenzhen"));
    }

    @Test
    public void testJoinOnJoinWithNullButUseDefaultValue() {
        String result = Joiner.on("#").useForNull("DEFAULT").join(stringListWithNull);
        assertThat(result, equalTo("beijing#shanghai#guangzhou#shenzhen#DEFAULT"));
    }

    @Test
    public void testJoinOnAppendToStringBuilder() {
        final StringBuilder builder = new StringBuilder();
        StringBuilder resultBuilder = Joiner.on("#").useForNull("DEFAULT").appendTo(builder, stringListWithNull);
        assertThat(resultBuilder, sameInstance(builder));
        assertThat(resultBuilder.toString(), equalTo("beijing#shanghai#guangzhou#shenzhen#DEFAULT"));
        assertThat(builder.toString(), equalTo("beijing#shanghai#guangzhou#shenzhen#DEFAULT"));
    }

    @Test
    public void testJoinOnAppendToWriter() {
        try (FileWriter writer = new FileWriter(new File(targetFileName))) {
            Joiner.on("#").useForNull("DEFAULT").appendTo(writer, stringListWithNull);
            assertThat(Files.isFile().test(new File(targetFileName)), equalTo(true));
        } catch (IOException e) {
            fail("error.");
        }
    }

    @Test
    public void testJoiningByStreamSkipNull() {
        String result = stringListWithNull.stream()
                .filter(item -> item != null && !item.isEmpty())
                .collect(joining("#"));
        assertThat(result, equalTo("beijing#shanghai#guangzhou#shenzhen"));
    }

    @Test
    public void testJoiningByStreamUseDefaultValue() {
        String result = stringListWithNull.stream()
                //.map(item -> item == null || item.isEmpty() ? "DEFAULT" : item)
                .map(this::defaultValue).collect(joining("#"));
        assertThat(result, equalTo("beijing#shanghai#guangzhou#shenzhen#DEFAULT"));
    }

    private String defaultValue(final String item) {
        return item == null || item.isEmpty() ? "DEFAULT" : item;
    }

    @Test
    public void testJoinOnWitnMap() {
        String result = Joiner.on("#").withKeyValueSeparator("=").join(stringMap);
        assertThat(result, equalTo("beijing=shanghai#guangzhou=shenzhen"));
    }

    @Test
    public void testJoinOnWitnMapToAppendable() {
        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("error.");
        }
    }
}

# (二)拆分器[Splitter]

package com.jcx.guava.utilites;

import com.google.common.base.Splitter;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;

public class SplitterTest {

    @Test
    public void testSplitOnSplit() {
        List<String> result = Splitter.on("|").splitToList("hello|world");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(2));
        assertThat(result.get(0), equalTo("hello"));
        assertThat(result.get(1), equalTo("world"));
    }

    @Test
    public void testSplitOnSplitOmitEmpty() {
        List<String> result = Splitter.on("|")
                .omitEmptyStrings().splitToList("hello | world||");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(2));
        assertThat(result.get(0), equalTo("hello "));
        assertThat(result.get(1), equalTo(" world"));
    }

    @Test
    public void testSplitOnSplitOmitEmptyTrimResult() {
        List<String> result = Splitter.on("|").trimResults()
                .omitEmptyStrings().splitToList("hello|world||");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(2));
        assertThat(result.get(0), equalTo("hello"));
        assertThat(result.get(1), equalTo("world"));
    }

    @Test
    public void testSplitFixLength() {
        List<String> result = Splitter.fixedLength(3).splitToList("aaaabbbbcccc");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(3));
        assertThat(result.get(0), equalTo("aaaa"));
        assertThat(result.get(1), equalTo("bbbb"));
        assertThat(result.get(2), equalTo("cccc"));
    }

    @Test
    public void testSplitOnSplitLimit() {
        List<String> result = Splitter.on("#").limit(2).splitToList("hello#world#java");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(2));
        assertThat(result.get(0), equalTo("hello"));
        assertThat(result.get(1), equalTo("world#java"));
    }

    @Test
    public void testSplitOnPatternString() {
        List<String> result = Splitter.onPattern("\|").trimResults()
                .omitEmptyStrings().splitToList("hello | world|||java");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(3));
        assertThat(result.get(0), equalTo("hello"));
        assertThat(result.get(1), equalTo("world"));
        assertThat(result.get(2), equalTo("java"));
    }

    @Test
    public void testSplitOnPattern() {
        List<String> result = Splitter.on(Pattern.compile("\|")).
                trimResults().omitEmptyStrings().splitToList("hello | world|||java");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(3));
        assertThat(result.get(0), equalTo("hello"));
        assertThat(result.get(1), equalTo("world"));
        assertThat(result.get(2), equalTo("java"));
    }

    @Test
    public void testSplitOnSplitToMap() {
        Map<String, String> result = Splitter.on(Pattern.compile("\|")).trimResults().omitEmptyStrings()
                .withKeyValueSeparator("=").split("hello=HELLO | world=WORLD||");
        assertThat(result, notNullValue());
        assertThat(result.size(), equalTo(2));
        assertThat(result.get("hello"), equalTo("HELLO"));
        assertThat(result.get("world"), equalTo("WORLD"));
    }
}

 

以上是关于Google Guava - 字符串处理的主要内容,如果未能解决你的问题,请参考以下文章

[Google Guava]字符串处理:连接器拆分器字符匹配器

google Guava 快速入门

Google Guava官方教程

Google Guava之--cache

Google-Guava(Utilites)

Google-Guava(Utilites)