Skip to content
Advertisement

Grouping phrases in a string in Java

I have string

String in = "Row: 1, Seat: 1, Row: 1, Seat: 2, Row: 1, Seat: 3, Row 4: Seat 10, Row 5: Seat 8, Row 5: Seat 9

And i want to get it:

String out = "Row: 1, Seat: 1, Seat: 2, Seat: 3, Row 4: Seat 10, Row 5: Seat 8, Seat 9

How i can do this? Maybe via regular expressions?

Advertisement

Answer

Try this.

Map<String, List<String>> map = Stream.of(in.split("\s*,\s*"))
    .map(e -> e.split("\s*:\s*"))
    .collect(Collectors.groupingBy(a -> a[0], TreeMap::new,
        Collectors.mapping(a -> a[1], Collectors.toList())));

String out = map.entrySet().stream()
    .map(e -> e.getKey() + ": "
        + e.getValue().stream().collect(Collectors.joining(", ")))
    .collect(Collectors.joining(", "));

System.out.println(out);

output:

Row 1: Seat 1, Seat 2, Seat 3, Row 4: Seat 10, Row 5: Seat 8, Seat 10
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement