-4

I have a string like this

String input = "abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2";

I want to create a Map which looks like (after filtering out label3}

label1 -> abc xyz

label2 -> cde pqr

This is what I could do so far

  Map<String, String> result = Arrays.stream(inputString.split(" "))
                .filter(i -> !i.contains("label3"))
                .map(i -> i.split("//|"))
Eran
  • 387,369
  • 54
  • 702
  • 768
Andy897
  • 6,915
  • 11
  • 51
  • 86

1 Answers1

2

It can be done as follows:

Map<String, String> result = 
    Arrays.stream(input.split(" ")) // build a Stream<String>
          .filter(i -> !i.contains("label3")) // filter out the undesired label
          .map(i -> i.split("\\|")) // get a Stream<String[]> where each array should have two
                                    // elements
          .collect(Collectors.groupingBy(a -> a[1], // group by second array element
                                         Collectors.mapping(a -> a[0], // map to first array 
                                                                       // element
                                                            Collectors.joining(" "))));// join

Output Map:

{label1=abc xyz, label2=cde pqr}

Explanation:

After you map the String elements of the Stream into String arrays, you collect them to a Map using grouping by the second element of each array, then mapping to the first element of each array, and finally joining the Strings belonging to the same group into a single String.

Eran
  • 387,369
  • 54
  • 702
  • 768