Pergunta

I am reading in a file like:

Tom Boyscouts Red_Cross
Jim Boyscouts FLBA
Jerry FBLA Red_Cross


    while (file.ready()) {
        ArrayList<String> nameToOrg= new ArrayList<String>(Arrays.asList(file.readLine().split(" ")));
        String members = list.remove(0);

        for (String key : nameToOrg) {
            if (treemap.get(key) == null) {
                TreeSet<String> membersAdded = new TreeSet<String>();   //Declare new TreeSet
                membersAdded.add(members);                              //Add this member
                treemap.put(key, membersAdded);                         //put(key,TreeSet)
            }else{
                //.get the existing set of members

                //add this new member

                //.put back into map
            }   
        }
    }

    file.close();

The current output would be...

Boyscouts = [Jim]
FBLA = [Jerry]
Red_Cross = [Jerry]

The output I want would be

Boyscouts = [Jim, Tom]
FBLA = [Jerry, Jim]
Red_Cross = [Jerry, Tom]

I am mostly being tripped up by else statement in my for loop. My professor gave us the pseudo-code, but I am not exactly sure how to .get the existing set of members from a TreeSet, and then update it.

EDIT: Thanks! Both of you had great answers, and really helped me out.

Foi útil?

Solução

Use Map.get() and Map.put() methods.

A note about this process : you may ask "why the hell do I need to reinsert the item"? Isn't it enough to just update it? Well, unfortunately not, because the map doesn't know about the change.

Let's say we've got a binary search tree (say, a TreeMap in Java) :

                   2
                1     3

If you update the record with 1 to 4, the map won't notice the change and you'll end up with an invalid BST :

                   2
                4     3

Now, an odd situation might happen that bst.contains(4) returns false while bst.keySet().contains(4) returns true.

For more details, you can see this SO question.

In this case, it shouldn't be needed though because the keys (Strings) are immutable.

Outras dicas

If key is already exist in map, still some code is missing in else part. like. Get list from map and add member, i.e.

 treemap.get(key).add(members);

Try it

 for (String key : nameToOrg) {
            if (treemap.get(key) == null) {
             TreeSet<String> membersAdded = new TreeSet<String>();   //Declare new TreeSet
             membersAdded.add(members);                              //Add this member
              treemap.put(key, membersAdded);                         //put(key,TreeSet)
            }else{
               treemap.get(key).add(members);//write here code
            }   
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top