Issue
I would like to get the values of the map and find the min value and construct a new CodesWithMinValue instance for each entry of the map. I want this using Java 11 streams, I can achieve this using multiple streams in more than one line(one for min value and one for transformation). is it possible to achieve in a single line using java 11 streams and collectors? Thank you.
public static void main(String[] args) {
Map<String, Integer> codesMap = getMockedCodesFromUpstream();
var minValue = Collections.min(codesMap.values());
var resultList = codesMap.entrySet().stream()
.map(e -> new CodesWithMinValue(e.getKey(), e.getValue(), minValue))
.collect(Collectors.toUnmodifiableList());
//is it possible to combine above three lines using stream and collectors API,
//and also can't call getMockedCodesFromUpstream() more than once. getMockedCodesFromUpstream() is a mocked implementation for testing.
//TODO: combine above three lines into a single line if possible
System.out.println(resultList);
}
private static Map<String, Integer> getMockedCodesFromUpstream(){
Map<String, Integer> codesMap = new HashMap<>();
codesMap.put("CDXKF", 44);
codesMap.put("GFDFS", 13);
codesMap.put("KUSSS", 10);
codesMap.put("EWSNK", 52);
codesMap.put("IOLHF", 21);
return codesMap;
}
private static class CodesWithMinValue{
public final String code;
public final int value;
public final int minValue;
public CodesWithMinValue(String code, int value, int minValue) {
this.code = code;
this.value = value;
this.minValue = minValue;
}
@Override
public String toString() {
return "CodesWithMinValue{" +
"code='" + code + '\'' +
", value=" + value +
", minValue=" + minValue +
'}';
}
}
Solution
I feel this can be simplified by refactoring and hiding away pieces of data rather than overengineering with Collectors.
private static BiFunction<Map<String, Integer>, Integer, List<MyNode>> getListOfMyNodeWithMinValue =
(map, minValue) ->
map.entrySet().stream()
.map(entry -> new MyNode(entry.getKey(), entry.getValue(), minValue))
.collect(Collectors.toList());
public static Function<Map<String, Integer>, List<MyNode>> getMyNodes =
map -> getListOfMyNodeWithMinValue.apply(map, Collections.min(map.values()));
This can be used thereafter as MyNode.getMyNodes.apply(inputMap)
.
Ignore my naming conventions. Just typed in whatever I felt. Hope you got the idea.
Answered By - Mohamed Anees A
Answer Checked By - Clifford M. (JavaFixing Volunteer)