Вот некоторые другие альтернативы:
Альтернатива 1 - разделение:
public static void main(String[] args) {
String input = "SID:SP19-BCS-123,FName:Aksam,LName:Basheer,CNIC:54321-1234567-1"
+ ",Age:22,CGPA:3.45,EmailAddress:SP19-BCS-123@cuilahore.edu.pk";
Map<String, String> resultMap = Arrays.stream(input.split(","))
.map(s -> s.split(":"))
.collect(Collectors.toMap(array -> array[0], array -> array[1]));
//Generate output
resultMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(entry ->
System.out.printf("Key: '%s' -> Value: '%s'%n"
, entry.getKey(), entry.getValue()));
}
Вариант вывода 1:
Key: 'Age' -> Value: '22'
Key: 'CGPA' -> Value: '3.45'
Key: 'CNIC' -> Value: '54321-1234567-1'
Key: 'EmailAddress' -> Value: 'SP19-BCS-123@cuilahore.edu.pk'
Key: 'FName' -> Value: 'Aksam'
Key: 'LName' -> Value: 'Basheer'
Key: 'SID' -> Value: 'SP19-BCS-123'
Альтернатива 2 - регулярное выражение:
public static void main(String[] args) {
String input = "SID:SP19-BCS-123,FName:Aksam,LName:Basheer,CNIC:54321-1234567-1"
+ ",Age:22,CGPA:3.45,EmailAddress:SP19-BCS-123@cuilahore.edu.pk";
String inputTrailingComma = String.format("%s,", input);
Matcher matcher = Pattern.compile("([^:]+):([^,]+),").matcher(inputTrailingComma);
while(matcher.find()) {
String key = matcher.group(1);
String value = matcher.group(2);
//Generate output
System.out.printf("Key: '%s' -> Value: '%s'%n", key, value);
}
}
Альтернатива вывода 2:
Key: 'SID' -> Value: 'SP19-BCS-123'
Key: 'FName' -> Value: 'Aksam'
Key: 'LName' -> Value: 'Basheer'
Key: 'CNIC' -> Value: '54321-1234567-1'
Key: 'Age' -> Value: '22'
Key: 'CGPA' -> Value: '3.45'
Key: 'EmailAddress' -> Value: 'SP19-BCS-123@cuilahore.edu.pk'