简体   繁体   中英

Writing a method that itterates over a Map, looks for Object entries that contain a value, adds this Object to a new set then returns that set

I am learning how to code in Java and struggling with this concept. I need to write a method that takes a char argument which exists within the Objects that are in a map.

It needs to return a currently non existing Set of Objects that contain this char value as a new Set after iterating over the map to find these objects.

The following is my current code which doesn't get my desired outcome, I believe the problem is in the if statement. I have done lots of different combinations of equals() and containsValue on the object and map and cannot seem to get it to return true.

public Set findObj(char aChar)
{
    Set<String> objSet = new HashSet();

    for (Object Obj: map1.values())
    {  
       if (map1.values().contains(aChar))
       {
           //if true add to objSet
       }
    }

    return objSet;
}

If it helps the Map is

Map<String,Obj> map1= new HashMap<>();

and the Object is created by a class and contains a 3 variables, 2 string and one being the char value I am trying to find within each iteration of the map.

you are correct the problem is mainly in your if statement, since you're iterating over the objects in the map, you should check if the current object contains the string not whether or not the map as a whole contains it

public Set findObj(char aChar) {
    Set<String> objSet = new HashSet();
    for (Object c : map1.values()) {
        if (c.toString().indexOf(aChar) >= 0) {
            //if true add to objSet
        }
    }
    return objSet;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM