Reputation: 1106
I'm trying to translate this algorithm I wrote in Java to Scala, but I'm having trouble with the containsValue()
method that is present in Java. I want to do something like if (hashMap.containsValue(value))
but I have looked through the scala documentation and have only found a contains(key) method. How do you implement or use hashmap.containsValue(value) in Scala I'm still new to Scala, but here's what I have so far in Scala:
def retString(s: String)
{
val map = new mutable.HashMap[Int, Char]
for (c <- s.toCharArray)
{
//if(!map.containsValue(c)) goes here
}
}
` The full algorithm I'm trying to convert is removeDuplicates I wrote in Java:
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;
}
Upvotes: 0
Views: 927
Reputation: 15490
to get know hashmap contaning this value you can use
hashMap.exists(_._2 == c)
you want something like this java to scala ;)
def removeDuplicates(s: Array[Char]): String = {
val hashMap = new scala.collection.mutable.HashMap[Integer, Character]()
var c = 0
var last = 0
while (c< s.length) {
if (!(hashMap.exists(_._2 == c))){
last+=1
s(last) = s(c)
hashMap.put(c, s(c))
}
c += 1
}
s(last) = '\0'
var result = ""
for (key <- hashMap.keySet) {
result += hashMap.get(key)
}
result
}
Upvotes: 1
Reputation: 1372
You might be glad to know that Scala collections contain a distinct
method:
> List(1,1,1,2,3,3,2,1).distinct
> List(1,2,3)
There is a Stack Overflow discussion on implementing distinctBy
which is somewhat useful to look at.
Upvotes: 0
Reputation: 41168
containsValue
is never going to be an efficient operation as it cannot use any of the special magic in HashMap.
As a result you can just iterate over the collection of values yourself and achieve exactly the same performance.
i.e. in Java:
for (Ob ob: map.values()) {
if (search.equals(ob))
return search;
}
Or alternatively just:
map.values().contains(search);
Upvotes: 0