Skip to content
Advertisement

How can I use an If-statement inside the Collector?

The output I require is like this :

"Versions" : [("0.1","true"),("0.2","false"),("0.3","true")]

The structure of this output is: Map<String, List<Pair<String, String>>>

Where "Versions" is the key of the Map and [("0.1","true"),("0.2","false"),("0.3","true")] this is the value of the Map.

Now, inside the Map we have a List like: List<Pair<String, String>> eg is this : [("0.1","true"),("0.2","false"),("0.3","true")]

Where "0.1","0.2","0.3" is the key of the Pair and "true","false","true" is the value of the Pair.

How do I write an if-else statement for this Pair? Where for a particular condition I want the value of the Pair to be returned as true or false?

Advertisement

Answer

You can utilize the existing implementation of map entry by invoking the static method Map.entry() that expects a key and a value (only for Java 9 and above) or by invoking the constructor of map entry directly:

new AbstractMap.SimpleEntry<>(key, value)

The attribute key is defined as final and value is mutable. If you are not satisfied with that (for instance, if you need an immutable object), you can define your own class Pair.

public class Pair<K, V> {
    private final K key;
    private final V value;
    
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }
    
    // getters
}

How do I write an if-else statement for this Pair? Where for a particular condition I want the value of the Pair to be returned as true or false?

For your conditional logic (if statements that you’ve mentioned) you can either it in-line inside the collector (as it shown below) or extract it into a separate method, which will be a better option if there are several conditions.

The only change needs to be done to your code is to replace the string concatenation inside the Collectors.mapping() with the expression that creates a map entry (or an instance of your custom class) which take the concatenated string representing a version as a key and the result of the condition as a value.

Collectors.mapping(cae -> Map.entry(cae.getMajorVersion() + "." + cae.getMinorVersion(),
                                    String.valueOf(your_condition)), 
            Collectors.toList())

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement