gpt4 book ai didi

Java 从数组列表中获取每个第二个元素并将其用作 HashMap 的值

转载 作者:行者123 更新时间:2023-12-02 02:17:02 25 4
gpt4 key购买 nike

我有以下文本文件:

1 dog

2 bark

3 broccoli

4 vegetable

5 orange

6 fruit

7 shark

8 fish

9 cat

10 meow

11 cricket

12 chirp

我想创建一个 HashMap ,其中文本文件中的每个偶数都有一个键,每个奇数都有一个值。随着时间的推移,此文本文件将添加更多行,因此我不想对其进行硬编码。

我通过列表读取纺织线并将其放入字符串数组列表中。

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Scanner;

public class brain {
public List<String> Payload1() throws IOException {
Scanner sc = new Scanner (new File("src/boot/Payload1.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());

}

return lines;
}

然后,我创建了一个 for 循环,使用 for 循环计数器在单独的字符串中获取每个偶数和奇数。

            String first = Hanes.Payload1().get(i);
String second = null;
if(Hanes.Payload1().size() > i + 1) {
second = Hanes.Payload1().get(i+1);
}
System.out.println(first);
System.out.println(second);
}

我不太确定如何将其实现为这样的 HashMap :

private HashMap<String,String> predictionFeatureMapping = new LinkedHashMap<String,String>();


public HashMap<String,String> predictionFeatureMapper() throws IOException {
predictionFeatureMapping = new LinkedHashMap<String,String>();

return predictionFeatureMapping;
}

最佳答案

public Map<String, String> Payload1() throws IOException {
Scanner sc = new Scanner (new File("src/boot/Payload1.txt"));
Map<String, String> fileMap = new LinkedHashMap<String, String>();
int counter = 1;
String key = "";
while (sc.hasNextLine()) {
if(counter % 2 != 0) {
key = sc.nextLine();
}else {
fileMap.put(key, sc.nextLine());
}
counter++;
}
sc.close();
return fileMap;
}

您可以将键值存储在字符串中,然后在拥有与之关联的值时在下一行中使用 put() 函数。模数只是决定你是在关键线还是值(value)线上。如果您仍然想返回所有行的列表以供其他用途,请使用相同的逻辑来创建 HashMap :

public Map<String, String> getFileMap(List<String> list){
Map<String, String> fileMap = new LinkedHashMap<String, String>();
String key = "";
for(int x = 0; x < list.size(); x++) {
if((x + 1 ) % 2 != 0) {
key = list.get(x);
}else {
fileMap.put(key, list.get(x));
}
}
return fileMap;
}

关于Java 从数组列表中获取每个第二个元素并将其用作 HashMap 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com