BSJ BSJ - 27 days ago 11
Java Question

Count and remove duplicates in a list of strings but add the duplicate count to the key (any idiomatic java8-esque way?)

I have an input string (delimited with

&
) containing the following terms :

GenericRequest.param[i]
SpecificRequest.param[i]=XYZ
GenericRequest.param[i]


I would like the output to get "consolidated" (and delimited with a
&
) with a minor twist:

GenericRequest.param[i]=2
SpecificRequest.param[i]=XYZ


So far, I can
.split("&")
and
.filter(s -> s.endsWith("[i]")
but that leads me to individual strings; i need visibility into all strings so i can effectively count dupes, remove dupes and then add this extra bit of metadata to the relevant key (in this case, counting duplicates of
GenericRequest.param[i]
, removing duplicates, and augmenting it with
=2
.

I can accomplish this by building a frequency count of filtered keys (ending with
"[i]"
) and adding that to a list of unfiltered keys, but I just don't know how to do it in an idiomatic java8 way.

Edit: Here is what a complete string looks like

GenericRequest.param[i]&SpecificRequest.param[i]=XYZ&GenericRequest.param[i]


Here's what I've tried so far:

String str = "GenericRequest.param[i]&SpecificRequest.param[i]=XYZ&GenericRequest.param[i]";
String result = Arrays.asList(str
.split("&"))
.filter(s -> s.endsWith("[i]");
.magic(?);

Answer

Try this, first am grouping by key and counting its value, then mapping key and value to a String

    String str = "GenericRequest.param[i]&SpecificRequest.param[i]=XYZ&GenericRequest.param[i]";
    Map<String, Long> map = Arrays.stream(str.split("&")).collect(Collectors.groupingBy(s -> s, Collectors.counting()));
    System.out.println(map);
    List<String> list = map.entrySet().stream().sorted(Map.Entry.comparingByKey())
            .map(e -> e.getKey() + (e.getValue() == 1 ? "" : "=" + e.getValue())).collect(Collectors.toList());
    System.out.println(list);

output

{SpecificRequest.param[i]=XYZ=1, GenericRequest.param[i]=2}
[GenericRequest.param[i]=2, SpecificRequest.param[i]=XYZ]
Comments