Search code examples
javajava-streamguavamultimap

Data handling of HashMultimap


I have a HashMultimap

Multimap<String, String> map = HashMultimap.create();

The data I put into the map is

map.put("cpu", "i9");
map.put("hang", "MSI");
map.put("hang", "DELL");
map.put("hang", "DELL");
map.put("cpu", "i5");
map.put("hang", "HP");
map.put("cpu", "i7");

I have a stream

String joinString = map.entries().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining(" OR "));

I need the output to be

(hang=HP OR hang=MSI OR hang=DELL) AND (cpu=i9 OR cpu=i5 OR cpu=i7)

I need an AND in between the keys. How can I do that?


Solution

  • Use the Map view:

    String joined = map.asMap()
            .entrySet()
            .stream()
            .map(e -> e.getValue()
                    .stream()
                    .map(v -> e.getKey() + "=" + v)
                    .collect(Collectors.joining(" OR ", "(", ")")))
            .collect(Collectors.joining(" AND "));