Search code examples
javalambdajava-streamoption-typetreemap

Java Map getValue not possible


I got a code which gets all minimum values from a list called frequencies. Then it puts the min values with the percentage of total values into a String. To calculate the percentage I want to call minEntryes.getValue()(minEntryes is the Map<String, Integer> with all the min values in it), but it does not work. My code:

    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("'"));
    }

The compiler tells me to call get(String key) but I don't know the key. So my code to get it into the Map is way to complicated, I know, but I can't use Optional in this case(the task prohibits it). I tried to do it more simple but nothing worked.

I could get a key from minEntryes.forEach, but im wondering if there's a better solution for this.


Solution

  • It's not clear to me what you are trying to do, but if the question is how to get the value without knowing the key:

    1st method: Use an for loop

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

    2nd method: Iterator "hack" (If you know there is always one value)

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