1

I have a Map with the following values:

map.of.list={\
  {'2','4'} : '1', \
  {'4','6'} : '2', \
  {'6','8'} : '3' \
 }

@Value("#{${map.of.list}}")
private Map<List<Integer>, Integer> integerMap;

How can I convert this to a Map<Range<Integer>, Integer> rangesMap?

Type for Range is org.springframework.data.domain.Range.

9
  • is Range a guava.Range?? Sep 8, 2020 at 8:46
  • no. it is org.springframework.data.domain.Range
    – misnomer42
    Sep 8, 2020 at 8:46
  • What's the type of the map.of.list data?
    – aioobe
    Sep 8, 2020 at 8:50
  • @aioobe String
    – misnomer42
    Sep 8, 2020 at 8:58
  • @misnomer42, oh! That makes the situation slightly more complicated. Could you provide a self-contained example program with the given input as a String variable, and a variable to hold the output?
    – aioobe
    Sep 8, 2020 at 9:04

2 Answers 2

1

With this setup:

// Sample input
Map<List<Integer>, Integer> input = new HashMap<>();
input.put(List.of(1, 3), 5);
input.put(List.of(4, 7), 8);

// Map to hold the result
Map<Range<Integer>, Integer> result = new HashMap<>();

You can do it using...

Traditional for loop

// Code to convert
for (Map.Entry<List<Integer>, Integer> entry : input.entrySet()) {

    // Convert list key to Range
    List<Integer> key = entry.getKey();
    int from = key.get(0);
    int to = key.get(1);
    Range range = Range.rightOpen(from, to);

    Integer value = entry.getValue();
    
    result.put(range, value);
}

Using entrySet and toMap

Map<Range<Integer>, Integer> result = input.entrySet()
        .stream()
        .collect(Collectors.toMap(
                e -> Range.rightOpen(e.getKey().get(0), e.getKey().get(1)),
                Map.Entry::getValue
        ));

Using forEach as suggested by misnormer42

Map<Range<Integer>, Integer> result = new HashMap<>();
input.forEach((keys, values) -> {
    Range<Integer> integerRange = Range.rightOpen(keys.get(0), keys.get(1));
    ranges.put(integerRange, values);
});
return result;
0
1

I can suggest to solve this problem in the following way:

public final class ConversionUtils {

    private ConversionUtils() {
    }

    public static Map<Range<Integer>, Integer> convertTo(Map<List<Integer>, Integer> fromProperties) {
        Map<Range<Integer>, Integer> result= new HashMap<>();
        fromProperties.forEach((keys, values) -> {
            Range<Integer> integerRange = Range.rightOpen(keys.get(0), keys.get(1));
            ranges.put(integerRange, values);
        });
        return result;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.