读取文本文件并存储在hashmap中。然后按顺序排序 [英] read text file and store in hashmap. Then sort in order
本文介绍了读取文本文件并存储在hashmap中。然后按顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
name1 134.2
name2 456.7
name3 265.3
...
...
我读取文本文件并存储在HashMap
之后,我想排序(按最高值),但问题是,因为我排序在字符串中的值,我不能比较它。
So..is有办法将textfile的值以double或integer的形式放入hashmap中吗?
import java.io. *;
import java.util。*;
class Test
{
public static void main(String [] args)throws FileNotFoundException {
Scanner scanner = new Scanner新的FileReader(score.txt));
HashMap< String,String> map = new HashMap< String,String>();
while(scanner.hasNextLine()){
String [] columns = scanner.nextLine()。split(\t\t);
map.put(列[0],列[1]);
}
System.out.println(map);
$ div $解析方案
是,使用 HashMap< String,Double>
,并在输入值时,使用 Double.parseDouble()
。
<你可以用
Float
而不是 Double
,但使用Double通常会更有意义)。 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);
}
}
解决方案
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).
这篇关于读取文本文件并存储在hashmap中。然后按顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文