Home > Enterprise >  Printing unique strings in HashMap
Printing unique strings in HashMap

Time:01-11

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

}

CodePudding user response:

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.

CodePudding user response:

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-

  •  Tags:  
  • Related