gpt4 book ai didi

java - Scala HashMap containsValue 方法

转载 作者:行者123 更新时间:2023-12-01 08:01:58 25 4
gpt4 key购买 nike

我正在尝试将我用 Java 编写的算法转换为 Scala,但我在使用 Java 中的 containsValue() 方法时遇到了问题。我想做一些类似于 if (hashMap.containsValue(value)) 的事情,但我查看了 scala 文档,只找到了一个 contains(key) 方法。 如何在 Scala 中实现或使用 hashmap.containsValue(value) 我对 Scala 还很陌生,但到目前为止,我在 Scala 中已经掌握了以下内容:

def retString(s: String)
{
val map = new mutable.HashMap[Int, Char]
for (c <- s.toCharArray)
{
//if(!map.containsValue(c)) goes here
}

}

`我尝试转换的完整算法是我用 Java 编写的removeDuplicates:

public static String removeDuplicates(char[] s)
{

HashMap<Integer, Character> hashMap = new HashMap<Integer, Character>();
int current = 0;
int last = 0;
for(; current < s.length; current++)
{
if (!(hashMap.containsValue(s[current])))
{
s[last++] = s[current];
hashMap.put(current, s[current]);

}
}
s[last] = '\0';
//iterate over the keys and find the values
String result = "";
for (Integer key: hashMap.keySet()) {
result += hashMap.get(key);
}
return result;

}

最佳答案

您可以使用exists :

map.values.exists(_ == c)

关于java - Scala HashMap containsValue 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24824887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com