1

i am currently making this code and it suppose to output the name of someone that a list of people didn't write his/her name. i just would like to ask how can i make the output like this using Map

Output: {Andrew}

Explanation : Jay wrote Susan , Susan wrote Jay, Andrew wrote Anna, Anna wrote Jay but nobody wrote Andrew.

Thanks!

public class Main {

        public static void main(String[] args) {

                Main func = new Main();

                System.out.println(func.test("Jay:Susan,Susan:Jay,Andrew:Anna,Anna:Jay"));
        }
        public PriorityQueue test(String c) {
                Map < String, String > hmap = new HashMap < > ();
                PriorityQueue a = new PriorityQueue();

                String b = c.replaceAll("[,]", "-");
                System.out.println(b);
                String[] d = b.split("-");

                for (int i = 0; i < d.length; i++) {

                        String names = d[i];
                        String[] temp;
                        String splitter = ":";

                        temp = names.split(splitter);
                        String aName = temp[0];
                        String cName = temp[1];

                        hmap.put(aName, cName);

                }

                System.out.println(hmap);

                return a;
        }

}

2 Answers 2

1

Just add this snippet before returning your priorityQueue:

 Set<String> keys= new HashSet<>( hmap.values());
        for(Map.Entry<String, String> map: hmap.entrySet())
        {
            String key=map.getKey();
            if(!keys.contains(key))
            {
                System.out.println(key);
                a.add(key);
            }
        }

I am simply checking which value is missing in the set which was supposed to be there.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this ! i've tried using something similar to this earlier but i did not realize i was mixing up the values with the keys.
np. Sometimes it may happen to anybody
0

Another way, using the functionality of Collections, would be to add the following before returning:

//Extract all the voters into a new hashset, this will be modified
Set<String> missing = new HashSet<>( hmap.keySet());
//Use Collections.removeAll() to remove all the values from the keyset
missing.removeAll(hmap.values());
//Add the results to your queue
a.addAll(missing);

Have a look at: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeAll-java.util.Collection-

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.