Java 8 stream map on entry set

前端 未结 5 1726
失恋的感觉
失恋的感觉 2020-12-29 19:22

I\'m trying to perform a map operation on each entry in a Map object.

I need to take a prefix off the key and convert the value from one type to another

相关标签:
5条回答
  • 2020-12-29 19:49

    On Java 9 or later, Map.entry can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry (as suggested in another answer) or AbstractMap.SimpleImmutableEntry would be the way to go.

    private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
       int subLength = prefix.length();
       return input.entrySet().stream().map(e -> 
          Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
       }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
    
    0 讨论(0)
  • 2020-12-29 19:51

    Simply translating the "old for loop way" into streams:

    private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
        int subLength = prefix.length();
        return input.entrySet().stream()
                .collect(Collectors.toMap(
                       entry -> entry.getKey().substring(subLength), 
                       entry -> AttributeType.GetByName(entry.getValue())));
    }
    
    0 讨论(0)
  • 2020-12-29 20:03

    Question might be a little dated, but you could simply use AbstractMap.SimpleEntry<> as follows:

    private Map<String, AttributeType> mapConfig(
        Map<String, String> input, String prefix) {
           int subLength = prefix.length();
           return input.entrySet()
              .stream()
              .map(e -> new AbstractMap.SimpleEntry<>(
                   e.getKey().substring(subLength),
                   AttributeType.GetByName(e.getValue()))
              .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

    any other Pair-like value object would work too (ie. ApacheCommons Pair tuple).

    0 讨论(0)
  • 2020-12-29 20:07

    Here is a shorter solution by AbacusUtil

    Stream.of(input).toMap(e -> e.getKey().substring(subLength), 
                           e -> AttributeType.GetByName(e.getValue()));
    
    0 讨论(0)
  • 2020-12-29 20:09

    Please make the following part of the Collectors API:

    <K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
      return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
    }
    
    0 讨论(0)
提交回复
热议问题