簡體   English   中英

Java1.8 將字符串拆分為鍵值對

[英]Java1.8 Split string into key-value pairs

我有一個像這樣的字符串但是非常大的字符串

String data = "created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z,city:Bangalore,Country:Ind";

Now:表示鍵值對,而,分隔鍵值對。 我想將鍵值對添加到 HashMap。我期待 output:-

{created=2022-03-16T07:10:26.135Z,timestamp=2022-03-16T07:10:26.087Z,city=Bangalore,Country=Ind}

我嘗試了多種方式,但我越來越喜歡那樣

{timestamp=2022-03-16T07, created=2022-03-16T07}

根據提供的信息,這里有一種方法可以做到。 它既需要分段分割,又需要限制分割的大小和位置。

String data = "created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z,city:Bangalore,Country:Ind";

Map<String, String> map =
        Arrays.stream(data.split(","))
        .map(str -> str.split(":", 2))
        .collect(Collectors.toMap(a -> a[0], a -> a[1]));

map.entrySet().forEach(System.out::println);        

請參閱在 IdeOne.com 上實時運行的代碼

city=Bangalore
created=2022-03-16T07:10:26.135Z
Country=Ind
timestamp=2022-03-16T07:10:26.087Z

正如我在評論中所說,由於重復鍵,您不能使用單個 map。 您可能需要考慮如下 class 來保存信息

class CityData {
    private String created;  // or a ZonedDateTime instance
    private String timeStamp;// or a ZonedDateTime instance
    private String city;
    private String country;
    @Getters and @setters
}

然后,您可以將您在 map 中擁有數據的給定國家/地區的所有城市分組,如下所示:

Map<String, List<CityData>>其中 Key 是國家。

var data="created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z";

var split = data.split(","); // splitting created and timestamp
var created = split[0].substring(8); // 8 is size of 'created:'
var timestamp = split[1].substring(10); // 10 is size of 'timestamp:'

Map<String, String> result = new HashMap<>();
result.put("created", created);
result.put("timestamp", timestamp);

output:{創建=2022-03-16T07:10:26.135Z,時間戳=2022-03-16T07:10:26.087Z}

您需要拆分數據並對此進行迭代,通過指定 index=2 在冒號上再拆分一次並將結果存儲在 Map 中。如果要保留順序,請使用 LinkedHashMap。

Map<String, String> map = new LinkedHashMap<>();
String data = "created:2022-03-16T07:10:26.135Z,timestamp:2022-03-16T07:10:26.087Z,city:Bangalore,Country:Ind";

String[] split = data.split(",");
for (String str: split) {
    String[] pair = str.split(":", 2);
    map.put(pair[0],pair[1]);
}

System.out.println(map);

Output: {created=2022-03-16T07:10:26.135Z, timestamp=2022-03-16T07:10:26.087Z, city=Bangalore, Country=Ind}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM