Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing unique strings in HashMap

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
        }

}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading