2017-12-27 903 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

相關問題