Java Map getValue not possible Java Map的getValue不可行

huangapple go评论142阅读模式
英文:

Java Map getValue not possible

问题

我有一段代码,它从名为frequencies的列表中获取所有最小值。然后,它将最小值与总值的百分比放入一个字符串中。为了计算百分比,我想调用minEntryes.getValue()(minEntryes是Map<String, Integer>,其中包含所有最小值),但它不起作用。我的代码:

    StringBuilder wordFrequencies = new StringBuilder();

    URL url = new URL(urlString); // urlString是函数的字符串参数

    AtomicInteger elementCount = new AtomicInteger(); // 所有不同字符的总计数

    Map<String, Integer> frequencies = new TreeMap<>(); // 存储所有字符频率的地方
    // 例如:e=10, r=4, (=3, g=4...

    // 读取和计算所有字符,运行正常
    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();
    }

    // 计算出现次数最少的字母
    // 在上面的示例中,这些是:r=4, g=4
    try (Stream<Map.Entry<String, Integer>> stream = frequencies.entrySet().stream()) {
        Map<String, Integer> minEntries = new TreeMap<>();
        stream
                .collect(Collectors.groupingBy(Map.Entry::getValue))
                .entrySet()
                .stream()
                .min(Map.Entry.comparingByKey())
                .map(Map.Entry::getValue)
                .ifPresent(key -> {
                    IntStream.rangeClosed(0, key.size())
                            .forEach(s -> minEntries.put(key.get(s).getKey(), key.get(s).getValue()));
                });

        wordFrequencies.append("\n\nSeltenste Zeichen: (").append(100 / (float) elementCount.get() * minEntries.values().stream().findFirst().orElse(0)).append("%)");
        minEntries.forEach((key, value) -> wordFrequencies.append("\n'" + key + "'"));
    }

编译器告诉我要调用get(String key),但我不知道键是什么。因此,我将它放入Map的代码太复杂,我知道,但在这种情况下我不能使用Optional(任务禁止使用它)。我尝试过更简单的方法,但都没有成功。

我可以从minEntries.forEach中获取一个键,但我想知道是否有更好的解决方案。

英文:

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&lt;String, Integer&gt; frequencies = new TreeMap&lt;&gt;();//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&lt;String&gt; stream = new BufferedReader(
new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)).lines()) {
stream
.flatMapToInt(CharSequence::chars)
.filter(c -&gt; !Character.isWhitespace(c))
.mapToObj(Character::toString)
.map(String::toLowerCase)
.forEach(s -&gt; {
frequencies.merge(s, 1, Integer::sum);
elementCount.getAndIncrement();
});
} catch (IOException e) {
return &quot;IOException:\n&quot; + 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&lt;Map.Entry&lt;String, Integer&gt;&gt; stream = frequencies.entrySet().stream()) {
Map&lt;String, Integer&gt; minEntryes = new TreeMap&lt;&gt;();
stream
.collect(Collectors.groupingBy(Map.Entry::getValue))
.entrySet()
.stream()
.min(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.ifPresent(key -&gt; {
IntStream i = IntStream.rangeClosed(0, key.size());
i.forEach(s -&gt; minEntryes.put(key.get(s).getKey(), key.get(s).getValue()));
});
wordFrequencies.append(&quot;\n\nSeltenste Zeichen: (&quot;).append(100 / elementCount.floatValue() * minEntryes.getValue().append(&quot;%)&quot;));
//this does not work
minEntryes.forEach((key, value) -&gt; wordFrequencies.append(&quot;\n&#39;&quot;).append(key).append(&quot;&#39;&quot;));
}

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.

答案1

得分: 2

不清楚你试图做什么,但如果问题是如何在不知道键的情况下获取值:

第一种方法:使用for循环

for (int value : minEntryes.values()) {
    // 使用 'value' 而不是 'minEntryes.getValue()'
}

第二种方法:迭代器 "hack"(如果你知道总是只有一个值)

int value = minEntryes.values().iterator().next();
// 使用 'value' 而不是 'minEntryes.getValue()'
英文:

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 &#39;value&#39; instead of &#39;minEntryes.getValue()&#39;
}

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

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

huangapple
  • 本文由 发表于 2020年8月5日 17:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63261772.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定