Java 地图 getValue 不可能

Java Map getValue not possible

我得到了一个代码,它从名为频率的列表中获取所有最小值。然后它将最小值和占总值的百分比放入一个字符串中。要计算我想调用 minEntryes.getValue() 的百分比(minEntryes 是 Map 中包含所有最小值),但它不起作用。我的代码:

    StringBuilder wordFrequencies = new StringBuilder();

    URL url = new URL(urlString);//urlString is a String parameter of the function

    AtomicInteger elementCount = new AtomicInteger();//total count of all the different characters

    Map<String, Integer> frequencies = new TreeMap<>();//where all the frequencies of the characters will be stored
//example: e=10, r=4, (=3 g=4...

    //read and count all the characters, works fine
    try (Stream<String> stream = new BufferedReader(
        new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)).lines()) {

      stream
          .flatMapToInt(CharSequence::chars)
          .filter(c -> !Character.isWhitespace(c))
          .mapToObj(Character::toString)
          .map(String::toLowerCase)
          .forEach(s -> {
            frequencies.merge(s, 1, Integer::sum);
            elementCount.getAndIncrement();
          });
    } catch (IOException e) {
      return "IOException:\n" + e.getMessage();
    }

    //counting the letters which are present the least amount of times
    //in the example from above those are
    //r=4, g=4
    try (Stream<Map.Entry<String, Integer>> stream = frequencies.entrySet().stream()) {
      Map<String, Integer> minEntryes = new TreeMap<>();
      stream
          .collect(Collectors.groupingBy(Map.Entry::getValue))
          .entrySet()
          .stream()
          .min(Map.Entry.comparingByKey())
          .map(Map.Entry::getValue)
          .ifPresent(key -> {
            IntStream i = IntStream.rangeClosed(0, key.size());
            i.forEach(s -> minEntryes.put(key.get(s).getKey(), key.get(s).getValue()));
          });

      wordFrequencies.append("\n\nSeltenste Zeichen: (").append(100 / elementCount.floatValue() * minEntryes.getValue().append("%)"));
                                                                                                 //this does not work
      minEntryes.forEach((key, value) -> wordFrequencies.append("\n'").append(key).append("'"));
    }

编译器告诉我调用 get(String key) 但我不知道密钥。所以我知道将它放入 Map 的代码很复杂,但在这种情况下我不能使用 Optional(任务禁止它)。我试着把它做得更简单,但没有任何效果。

我可以从 minEntryes.forEach 获取密钥,但我想知道是否有更好的解决方案。

我不清楚你要做什么,但如果问题是如何在不知道密钥的情况下获取值:

第一种方法:使用 for 循环

    for (int value : minEntryes.values()) {
        // use 'value' instead of 'minEntryes.getValue()'
    }

第二种方法:迭代器“hack”(如果您知道总有一个值)

    int value = minEntryes.values().iterator().next();
    // use 'value' instead of 'minEntryes.getValue()'