2017-12-27 901 views
5

我有类:如何使用Java 8和StringJoiner连接来自列表的两个字段?

public class Item { 

    private String first; 
    private String second; 

    public Item(String first, String second) { 
     this.first = first; 
     this.second = second; 
    } 
} 

而且此类对象的列表:

List<Item> items = asList(new Item("One", "Two"), new Item("Three", "Four")); 

我的目标是加入元素的列表,以便建立以下字符串:

One: Two; Three: Four; 

我我试图使用StringJoiner,但它看起来像它被设计用于处理一些简单类型的列表。

回答

9

你可以尝试这样的事情:

final String result = items.stream() 
     .map(item -> String.format("%s: %s", item.first, item.second)) 
     .collect(Collectors.joining("; ")); 

由于assylias在下面的评论中提到,最后;将错过使用这种结构。它可以手动添加到最终的字符串中,或​​者您可以简单地尝试由assylias建议的解决方案。

+1

你将错过最后';' – assylias

+0

您可以使用前缀/后缀超载了点。 – shmosel

+0

@assylias你说得对,谢谢你的收获! –

10

您可将商品映射到串接的字段,然后加入项目的字符串,它们用空格分隔:

String result = items.stream() 
        .map(it -> it.field1 + ": " + it.field2 + ";") 
        .collect(Collectors.joining(" ")); 
+0

非常感谢))) – Marian

2

第一步是加入field1field2

第二步是加入;

请注意,这不会在最后添加;

List<Item> items = asList(new Item("One", "Two"), new Item("Three", "Four")); 

String joined = items.stream() 
     // First step 
     .map(it -> it.field1 + ": " + it.field2) 
     // Second step 
     .collect(Collectors.joining("; ")); 

某种程度上更OO

或者更好的是:移动逻辑加盟field1field2到一个专门的方法:

public static class Item { 
    private String field1; 
    private String field2; 

    public Item(String field1, String field2) { 
     this.field1 = field1; 
     this.field2 = field2; 
    } 

    public String getField1And2() { 
     return field1 + ": " + field2; 
    } 

} 

,并使用一个流。

String joined = items.stream() 
     .map(Item::getField1And2) 
     .collect(Collectors.joining("; ")); 
+0

非常感谢))) – Marian

相关问题