Java8使用StringJoiner看这一篇就够了

在开发过程中,有时候需要打印集合中的对象的某个属性,为了格式化以前常用StrinigBuffer。

比如下面这种代码:

Set<Cat> catSet = new HashSet<>(2);

    @Before
    public void init() {
        Cat cat = new Cat();
        cat.setName("老大");
        cat.setAge(1);
        catSet.add(cat);
        Cat cat2 = new Cat();
        cat2.setName("老二");
        cat2.setAge(2);
        catSet.add(cat2);

    }

    @Test
    public void print1() {

        // 给出友好提示
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        Iterator<Cat> iterator = catSet.iterator();
        int seq = 0;
        while (iterator.hasNext()) {
            seq++;
            stringBuilder.append(seq);
            stringBuilder.append(":");
            stringBuilder.append(iterator.next().getName());
            if (seq != catSet.size()) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]");
        Assert.assertEquals("[1:老二,2:老大]", stringBuilder.toString());

    }

最近接触到Java8提供了StringJoiner,看到一篇不错的文章,翻译在此,文后给出改进方案,一行代码解决问题!

--------------------------------------------分割线-------------------------------------------------------------

添加元素
 

@Test
public void whenAddingElements_thenJoinedElements() {
    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
    joiner.add("Red")
      .add("Green")
      .add("Blue");
 
    assertEquals(joiner.toString(), "[Red,Green,Blue]");
}

如果想讲List添加到其中:

@Test
public void whenAddingListElements_thenJoinedListElements() {
    List<String> rgbList = new ArrayList<>();
    rgbList.add("Red");
    rgbList.add("Green");
    rgbList.add("Blue");
 
    StringJoiner rgbJoiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
 
    for (String color : rgbList) {
        rgbJoiner.add(color);
    }
 
    assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}

构造

private String PREFIX = "[";
private String SUFFIX = "]";
 
@Test
public void whenEmptyJoinerWithoutPrefixSuffix_thenEmptyString() {
    StringJoiner joiner = new StringJoiner(",");
  
    assertEquals(0, joiner.toString().length());
}
 
@Test
public void whenEmptyJoinerJoinerWithPrefixSuffix_thenPrefixSuffix() {
    StringJoiner joiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
  
    assertEquals(joiner.toString(), PREFIX + SUFFIX);
}

 toString() 方法得到当前连接对象的字符串形式。

没有指定前缀和后缀的Joiner对象将返回空字符串。

@Test
public void whenEmptyJoinerWithEmptyValue_thenDefaultValue() {
    StringJoiner joiner = new StringJoiner(",");
    joiner.setEmptyValue("default");
 
    assertEquals(joiner.toString(), "default");
}
 
@Test
public void whenEmptyJoinerWithPrefixSuffixAndEmptyValue_thenDefaultValue() {
    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
    joiner.setEmptyValue("default");
 
    assertEquals(joiner.toString(), "default");
}

可以调用joiner.setEmptyValue()函数,设置默认值。

Joiners组合使用

private String PREFIX = "[";
private String SUFFIX = "]";

@Test
public void whenMergingJoiners_thenReturnMerged() {
    StringJoiner rgbJoiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
    StringJoiner cmybJoiner = new StringJoiner(
      "-", PREFIX, SUFFIX);
 
    rgbJoiner.add("Red")
      .add("Green")
      .add("Blue");
    cmybJoiner.add("Cyan")
      .add("Magenta")
      .add("Yellow")
      .add("Black");
 
    rgbJoiner.merge(cmybJoiner);
 
    assertEquals(
      rgbJoiner.toString(), 
      "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
}

两个joiner可以通过merge函数,组合在一起。

利用Stream API

 

@Test
public void whenUsedWithinCollectors_thenJoined() {
    List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
    String commaSeparatedRGB = rgbList.stream()
      .map(color -> color.toString())
      .collect(Collectors.joining(","));
 
    assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}

英文原文:https://www.baeldung.com/java-string-joiner

--------------------------------------------分割线-------------------------------------------------------------

改进

根据本文的学习对我们的代码进行改进:

第一版:

 @Test
    public void print() {
        StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
        Iterator<Cat> iterator = catSet.iterator();
        int seq = 0;
        while (iterator.hasNext()) {
            seq++;
            stringJoiner.add(seq + ":" + iterator.next().getName());
        }
        Assert.assertEquals("[1:老二,2:老大]", stringJoiner.toString());
    }

第二版:

   @Test
    public void print2() {
List<Cat> catList = new ArrayList<>(catSet);
        String result = IntStream.range(0,catList.size()).mapToObj(i->i+":"+ catList.get(i).getName()).collect(Collectors.joining(",", "[", "]"));
        Assert.assertEquals("[1:老二,2:老大]", result);
    }

一行代码,很简单,很优雅!!!

网上的一些其他例子:https://www.codota.com/code/java/classes/java.util.StringJoiner?openFrom=IDE_plugin_2.8.3

另外这个网站可以搜到很多很多很多类的用法,推荐收藏!

 

如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明明如月学长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值