0

I am working on a project where I am creating a TreeMap of past presidents and their blood types. The first step is to generate a map from blood type to presidents, and then to print it out alphabetically. I have that part correct, but I am struggling with the next part. For the second half of the project, I am supposed to then create an inverse mapping where the president is the key and the blood type is the value. I can't seem to figure out how to get this to work without screwing up the first half. I've attached a picture of what the output is supposed to look like. I appreciate any feedback. Output Image

    import java.io.*;
    import java.util.*;

public class BloodBank
{
    public static void main(String[] args) throws Exception
    {
        BufferedReader infile = new BufferedReader( new FileReader( "type2pres.txt" ) );
        TreeMap<String,TreeSet<String>> type2pres = new TreeMap<String,TreeSet<String>>();

        while ( infile.ready() )
        {
            ArrayList<String> tokens = new ArrayList<String>( Arrays.asList( infile.readLine().split(",") ) );
            String bloodType = tokens.remove(0); 

            type2pres.put( bloodType, new TreeSet<String>(tokens) );
        }



        for ( String type  : type2pres.keySet() ) 
        {   TreeSet<String> presidents = type2pres.get( type );
            System.out.print( type + "\t" );


            for ( String pres : presidents )
            {
                System.out.print( pres  + "\t" );

            }
            System.out.println();


        } 



    } // MAIN


} // BLOODBANK
Ironman131
  • 13
  • 2
  • 1
    You just need to make a second `Map>` and add the elements to it like you did previously, but reverse the key and value. – Jacob G. Apr 22 '17 at 16:05
  • Possible duplicate: http://stackoverflow.com/questions/20412354/reverse-hashmap-keys-and-values-in-java But your case is a little more complicated because you will need two loops: one over `type2pres.entrySet()` and another over each `entry.getValue()`. This shouldn't interfere with your first map, because you need to make another for the reverse mapping. – Radiodef Apr 22 '17 at 16:14

2 Answers2

0
for ( String type  : type2pres.keySet() ) 
    {   
        TreeMap<String, String> map = new TreeMap<>();

        for (String president : type2pres.get(type)) {
            map.put(president, type);
            System.out.print( president + "\t" );
            System.out.println( type + "\t" );
        }

    } 
Mircea Mi
  • 26
  • 4
  • If I wanted to make sure the presidents were alphabetized but not the blood type, how would I go about doing so? – Ironman131 Apr 22 '17 at 17:02
0

You can print all the names in ascen order with Java 8's stream(), e.g.:

type2pres.entrySet().stream()
.flatMap(e -> e.getValue().stream().map(v -> v + "\t" + e.getKey()))
.sorted()
.forEach(System.out::println);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102