[英]I need help creating this Java Map?
I have a text file with this data:我有一个包含这些数据的文本文件:
a, 0, 10, 7,
b, 22, 0, 13,
c, 4, 12, 0
I want to create a Map with the key being the letter and the value being an ArrayList<Integer>
of the int
values associated with that letter.我想创建一个 Map,键是字母,值是与该字母关联的
int
值的ArrayList<Integer>
。
This is what I have tried:这是我尝试过的:
List<String> list = new ArrayList<String>();
while(scanner.hasNext()){
list.add(scanner.nextLine());
}
Map <String, ArrayList <Integer>> map = new HashMap();
//map.put(list.get(0).charAt(0), value);
}
The key part of the map works by getting the letter but I am unsure how to correctly implement the value to be the ArrayList <Integer>
values. map 的关键部分通过获取字母来工作,但我不确定如何正确地将值实现为
ArrayList <Integer>
值。
You only need one loop to iterate over the lines and grab the first + remaining columns您只需要一个循环来遍历行并获取第一个 + 剩余的列
For example,例如,
Map <String, ArrayList <Integer>> map = new HashMap<>();
while(scanner.hasNext()){
String[] parts = scanner.nextLine().split("\\s*,\\s*");
List<Integer> numbers = Arrays.stream(Arrays.copyOfRange(parts, 1, parts.length))
.map(Integer::parseInt)
.collect(toList());
map.put(parts[0], numbers);
}
Note: You may want to remove the commas from the end of each line注意:您可能需要删除每行末尾的逗号
Well, here is a somewhat different approach.好吧,这是一种有些不同的方法。
Files.lines
method to stream the lines.Files.lines
方法 stream 行。String sourceFile = "<Your file here>";
Map<String, List<Integer>> map;
try {
map = Files.lines(Path.of(sourceFile))
.map(String::trim)
.map(str -> str.split("\\s*,\\s*"))
.collect(Collectors.toMap(a -> a[0], a -> Arrays
.stream(Arrays.copyOfRange(a, 1, a.length))
.map(Integer::valueOf)
.collect(Collectors.toList()),
(list1,list2)-> {list1.addAll(list2); return list1;}));
} catch (IOException fne) {
fne.printStackTrace();
}
map.entrySet().forEach(System.out::println);
So given a file like the following:所以给定一个如下文件:
a, 0, 10, 7,
b, 22, 0, 13,
c, 4,12,0
c,4,12,12
a,9,2,3
Prints印刷
a=[0, 10, 7, 9, 2, 3]
b=[22, 0, 13]
c=[4, 12, 0, 4, 12, 12]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.