Java使用(key = string,value = line number)将文件中的所有字符串加载到Set数据结构中

问题描述 投票:-1回答:1

我一直在尝试用键值实现Set数据结构。我有一个txt文件(EOL),有一个字符串,行号是这样的:

Adam,1
Mary,2
Michael,3

我的目标是将此key-value存储在Set中。

这是我的代码:

public class Main {

public static void main(String[] args)throws Exception
{

    Scanner scanner = new Scanner(new FileReader("C:\\Users\\musti\\Desktop\\demo.txt"));

    HashMap<String,Integer> mapFirstfile = new HashMap<String,Integer>();

    while (scanner.hasNextLine()) {
        String[] columns = scanner.nextLine().split(",");

        mapFirstfile.put(columns[0],Integer.parseInt(columns[1]));        }
    // HashMap sıralı yazdırmaz, LinkedHashSet sıralı tutar, ama ekstradan linkedlist lazım.
    System.out.println(mapFirstfile);
    System.out.println(mapFirstfile.keySet());
    System.out.println(mapFirstfile.values());

    Set<HashMap> setFirstfile = new HashSet<HashMap>();


}
java hashmap set
1个回答
0
投票

这实际上不是答案,但是评论太久了...

首先,Set是唯一(就equals()而言)值的结构。

因此,以上代码实际上使用了正确的结构Map,您在其中将String映射到数字(Integer)。

问题1

是否需要数字,是否在文件中?您可以通过输入来计算]

Adam
Mary
Michael

我们知道,亚当在第一行...

edit 1:您可以使用每次进入循环都会增加的计数器。 Java API中没有为您做的事情...

问题2

在您的问题中,我缺少有关什么不起作用的信息...您的期望不正确吗?

问题3

如果重复,该怎么办?

Alfa
Bravo
Alfa

可以,在第三行将Alfa重新映射为3吗?

问题4

您使用Set的动机是什么?

正如我在Set中所写的,包含“单个”项目。如果您的商品包含多个字段,则可以将其包装在Object中,但看不到好处...

类似

class Item {
    String line;
    int lineNumber;
    // TODO: 1 add constructors
    // TODO: 2 add getter & setters
    // TODO: 3 implement equals() and hashCode()
}

并像这样将其添加到Set

Set mySet = ...
mySet.add(new Item(line, counter)); // you need to add such constructor
© www.soinside.com 2019 - 2024. All rights reserved.