Given the following String:
String s = "DIMENSION 24cm 34cm 12cm DETAILED SPECIFICATION Twin/Twin XL Flat Sheet: 105"l x 74"w. CARE For best results, machine wash warm with like colors. COLOURS red blue green";
Keys are = DIMENSIONS, DETAILED SPECIFICATION, CARE, COLOURS
We need to create Map<String,String> where keys will be as provided above and corresponding text will be the value.
The map's contents will look like:
DIMENSION: 24cm 34cm 12cm,
DETAILED SPECIFICATION: Twin/Twin XL Flat Sheet: 105"l x 74"w,
CARE: For best results, machine wash warm with like colors,
COLOURS: red blue green
And not necessary that all these keys and values are present in the string.
Suppose the key CARE is not present in the input String:
String s = "DIMENSION 24cm 34cm 12cm DETAILED SPECIFICATION Twin/Twin XL Flat Sheet: 105"l x 74"w. COLOURS red blue green";
The map's contents will look like:
DIMENSION: 24cm 34cm 12cm,
DETAILED SPECIFICATION: Twin/Twin XL Flat Sheet: 105"l x 74"w,
COLOURS: red blue green
I.e. if a key is absent in the given string then the corresponding value will be also absent. For instance, DIMENSION key is absent and string starts like "DETAILED SPECIFICATION ... ".
As the string doesn't have delimiters, I am unable to create a map from it.
With plane Java, I am able to do like this:
if(s.contains("ASSEMBLY")) {
ass = s.substring(s.indexOf("COLOURS") + 8);
s = s.replaceAll(s.substring(s.indexOf("COLOURS")),"");
}
if(s.contains("OVERALL")){
ov = s.substring(s.indexOf("CARE") + 5);
s = s.replaceAll(s.substring(s.indexOf("CARE")),"");
}
if(s.contains("CARE")){
care1 = s.substring(s.indexOf("DETAILED SPECIFICATION") + 24);
s = s.replaceAll(s.substring(s.indexOf("DETAILED SPECIFICATION")),"");
}
if(s.contains("DIMENSIONS")){
de1 = s.substring(s.indexOf("DIMENSIONS") + 11);
s =s.replaceAll(s.substring(s.indexOf("DIMENSIONS")),"");
}
If we have delimiter, then I am able to do it like this.
Map<String, String> map = Stream.of(s)
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));