0

I have to print out the top 5 contents from a txt file using a HashMap. Here is a sample of what is in the text file.

A01 Web app
A02 Engagement
A03 Embedding
A04 Impressions
A05 Influencer
A06 Mention
A07 Microblogging
A08 Organic
A09 Reach
A10 Social graph
A11 User-generated content
A12 Affiliate marketing
A13 Bounce rate
A14 Call to Action
A15 Click through rate

etc....

Here is what i have so far:

 final int assumedLineLength = 16;
       File file = new File("src/hw7p1/Acronyms.txt");
     try {
    Scanner scan = new Scanner(file);
     HashMap<String, String> hashMap = new HashMap<String, String>((int)(file.length() / assumedLineLength) * 2);



    while(scan.hasNextLine()) {
        String[] columns = scan.nextLine().split(" ");
        hashMap.put(columns[0], columns[1]);


    }

    for (String key : hashMap.keySet()) {

    System.out.println(key +" " + hashMap.get(key));}

} catch (IOException e) {
    e.printStackTrace();

}
     }}

This is what I am getting for my output:

 A87 Big
 A88 Data
 A01 Web
 A89 Database
 A02 Engagement
 A03 Embedding
 A04 Impressions
 A05 Influencer
 A06 Mention
 A07 Microblogging
 A08 Organic
 A09 Reach
 A90 Data
 A91 Data
 A92 Relational
 A93 Hybrid
 A94 IDE
 A95 Native
 A96 NFC
 A97 Responsive
 A10 Social
 A98 SDK
 A11 User-generated
 A99 Content

For some reason it is mixing some of the out put around when it is suppose to look the example above. Any help would be greatly appreciated. Thank you

  • there are no guarantees to the order of a HashMap. use a [**LinkedHashMap**](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html) – Ousmane D. Nov 14 '17 at 22:07
  • Is it possible to use the sort method? – confused678 Nov 14 '17 at 22:09
  • `linkedHashMap.entrySet().stream().sorted().collect(PassInCollector);` or you can use `Collections.sort`. you can also pass in a `Comparator` object into the `sorted` method and define _what to sort by_. – Ousmane D. Nov 14 '17 at 22:14

2 Answers2

2

I would Suggest using a LinkedHashMap as it preserves the order of input

 LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>((int)(file.length() / assumedLineLength) * 2);
1

Try:

Map<String, String> hashMap = new LinkedHashMap<String, String>(
                    (int) (file.length() / assumedLineLength) * 2);
Vijaya Pandey
  • 4,252
  • 5
  • 32
  • 57