2016-08-30 39 views
2

我一直在四處尋找重建地圖,但不能拿出使用Java 8優雅實用的解決方案這是我要解決的問題:功能的解決方案,從字符串

我有「序列化」的地圖進入一個字符串,例如

{ type -> 'fruit', 
    color -> 'yellow', 
    age -> 5 } 

將成爲:

type:fruit;color:yellow;age:5 

現在,我要重新從字符串的原始地圖

Arrays.stream(input.split(";")) 
     .map(v -> v.split(":")) 
     .collect(Collectors.toMap(c -> c[0], c -> c.[1]); 

注意上面的代碼將導致NullPointerException如果沒有「:」在列表中,這可以與解決:

c.length > 1 ? c[1] : c[0] 

但是,這感覺不對。任何使用Java8 API的建議或替代方案?

+4

如果在值內有';'或':'會怎麼樣? –

回答

3

這個工作對我來說:

class StreamToInflateStringToMap { 
    private static Function<String, String> keyMapper = 
      s -> s.substring(0, s.indexOf(":")); 
    private static Function<String, String> valueMapper = 
      s -> s.substring(s.indexOf(":") + 1); 

    public static Map<String, String> inflateStringToMap(String flatString) { 
     return Stream.of(flatString.split(";")). 
       collect(Collectors.toMap(keyMapper, valueMapper)); 
    } 

    public static void main(String[] args) { 
     String flatString = "type:fruit;color:yellow;age:5"; 
     System.out.println("Flat String:\n" + flatString); 
     Map<String, String> inflatedMap = inflateStringToMap(flatString); 
     System.out.println("Inflated Map:\n" + inflatedMap); 
    } 
} 

請注意,我假定你的意思是你想要的分號失蹤時的解決方案(即:只有一個在地圖項目)。如果沒有冒號,那麼拋出異常是完全正確的,因爲這意味着在字符串中沒有定義映射,並且必須將錯誤值傳遞給該方法。

Alexey Romanov提出的評論也是有效的:你能保證在內容中找不到分隔字符作爲實際鍵/值字符串的一部分嗎?如果沒有,那麼你會遇到麻煩(無論你使用什麼方法膨脹),因此可能需要驗證放入地圖原始副本的值。

另請注意,我已將Function<String, String>映射器聲明爲類的靜態成員,但是如果您不需要在其他任何地方使用它們,並且您認爲它不會生成代碼,則可以將它們直接拖入Stream流中太醜了。

此外,通過Java 8 API的一些狩獵發現了一種替代方法,以分隔符分隔的String創建Stream。您可以使用Pattern.splitAsStream(CharSequence)方法,是這樣的:

private static final Pattern SINGLE_SEMICOLON = Pattern.compile(";"); 

public static Map<String, String> inflateStringToMap(String flatString) { 
    return SINGLE_SEMICOLON.splitAsStream(flatString). 
      collect(Collectors.toMap(keyMapper, valueMapper)); 
} 

(注意warning in the API的餵養可變CharSequence類型,如StringBuildersplitAsStream方法。)

0

如果你有番石榴,你可以使用

Splitter.on(';').withKeyValueSeparator(':').split(input) 
相關問題