read text file and store in hashmap. Then sort in order

好久不见. 提交于 2019-12-12 09:27:57

问题


File is like this:

name1   134.2
name2   456.7
name3   265.3
...
...

I read the text file and store in HashMap after that I want to sort in order(by the highest value) but the problem is that because I sort the values in String, I cant compare it. So..is there a way to put the values of textfile into hashmap in double or integer form?

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


class Test 
{
    public static void main(String[] args) throws FileNotFoundException {

Scanner scanner = new Scanner(new FileReader("score.txt"));

        HashMap<String, String> map = new HashMap<String, String>();

        while (scanner.hasNextLine()) {
            String[] columns = scanner.nextLine().split("\t\t");
            map.put(columns[0], columns[1]);
        }

        System.out.println(map);
    }
}

回答1:


Yes, use HashMap<String,Double> and when putting in the values, convert them to double using Double.parseDouble().

(You can do the same with Float rather than Double, but using Double makes so much more sense usually).




回答2:


The HashMap does not guarantee order:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This would mean that sorting your hash map would be useless. If you need to load key value pairs like those, you could consider implementing your own class which has the required fields and implements the Comparible interface.

This will allow you to load your objects and then just call Collections.sort() to sort the list of custom objects.



来源:https://stackoverflow.com/questions/13513667/read-text-file-and-store-in-hashmap-then-sort-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!