Home > OS >  Java1.8 Split string into key-value pairs
Java1.8 Split string into key-value pairs

Time:03-18

I have a string like this but very big string

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

Now : indicates key-value pairs while , separates the pairs. I want to add the key-value pairs to a HashMap. I am expecting output:-

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

I tried in multiple way but I am getting like that

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

CodePudding user response:

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: {created=2022-03-16T07:10:26.135Z, timestamp=2022-03-16T07:10:26.087Z}

CodePudding user response:

You need to split the data and iterate on this, split it one more time on colon by specifying index=2 and store the result in a Map. If you want to preserve the order use 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}

CodePudding user response:

Based on the information provided, here one way to do it. It required both splitting in sections and limiting the size and location of the split.

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);        

prints

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

As I said in the comments, you can't use a single map because of the duplicate keys. You may want to consider a class as follows to hold the information

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