我有一个充满Strings
的TreeSet
,我想用它来查看其中的任何键是否以集合之外的字符串开头,并且能够获取该特定 key 并用它执行某些操作(将其放入字符串中)例如,我的 String
是 test 1 2 3
并且我有一个 key
在 test 1 2
集合中,它应该返回 true 并告诉我 key 。我使用 TreeSet 的原因是因为我需要一种不区分大小写的方式来读取 yaml 文件中的键。在使用之前我已经在集合上使用了迭代器
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext())
if (myString.startsWith(itr.next())){ }
但我无法找到使 if 语句成立的关键。
最佳答案
你真的很接近...只是这一行是错误的
if (myString.startsWith(itr.next())){ }
应该是这样 - 因为 key 应该以 myString
开头。
String theKey = null;
while(itr.hasNext()) {
theKey = itr.next();
if (theKey.startsWith(myString)) {
return theKey;
}
}
return null;
关于java - 检查 TreeSet 中的键是否以 String 开头,并获取该键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446233/