我想知道,如何获取TreeMap中的密钥,以获取密钥的信息?例如,我已经声明了这样的TreeMap:
TreeMap miniDictionary = new TreeMap<DictionaryTerm,Integer>(new TermComparator());
DictionaryTerm只是一个简单的类,它只有两个变量,“String term”和“int number”。
TermComparator是一个比较两个键的类:
class TermComparator implements Comparator<DictionaryTerm> {
@Override
public int compare(DictionaryTerm e1, DictionaryTerm e2) {
return e1.getTerm().compareTo(e2.getTerm());
}
}
让我们假设TreeMap已经有这样的条目:(“LedZeppelin”,55) - &gt; 25 其中(LedZeppelin,55)是关键,其值是25。
现在让我说我有这个变量:
DictionaryTerm aTerm = new DictionaryTerm("LedZeppelin",100);
如何在TreeMap中找到“aTerm”并获取其读取信息的关键字?考虑到我创建的TermComparator,按字符串术语进行比较。
先谢谢。
答案 0 :(得分:2)
我想您有兴趣从#!/bin/bash
declare -i lines=0
declare -i words=0
declare -i chars=0
declare -i upper=0
declare -i lower=0
declare -i digit=0
declare -i punct=0
oifs="$IFS"
# Read line with new IFS, preserve whitespace
while IFS=$'\n' read -r line; do
# parse line into words with original IFS
IFS=$oifs
set -- $line
IFS=$'\n'
# Add up lines, words, chars, upper, lower, digit
lines=$((lines + 1))
words=$((words + $#))
chars=$((chars + ${#line} + 1))
for ((i = 0; i < ${#line}; i++)); do
[[ ${line:$((i)):1} =~ [[:upper:]] ]] && ((upper++))
[[ ${line:$((i)):1} =~ [[:lower:]] ]] && ((lower++))
[[ ${line:$((i)):1} =~ [[:digit:]] ]] && ((digit++))
[[ ${line:$((i)):1} =~ [[:punct:]] ]] && ((punct++))
done
done
echo " $lines $words $chars $file"
echo " upper: $upper, lower: $lower, digit: $digit, punct: $punct, \
whitespace: $((chars-upper-lower-digit-punct))"
获取与$ cat dat/captnjackn.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
(along with 2357 other pirates)
相等的密钥,因为获取该值很容易($ bash wcount3.sh <dat/captnjackn.txt
5 21 108
upper: 12, lower: 68, digit: 4, punct: 3, whitespace: 21
)。
要获取密钥,您可以使用TreeMap
。此方法返回&#34;小于或等于给定键的最大键,或者如果没有这样的键&#34;则返回null,因此您必须首先检查null和相等:
aTerm
如果您想获得密钥和值,请使用floorEntry()
。