英文:
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<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.
答案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 '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()'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论