简体   繁体   中英

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.

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.

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.

  • allow for less specific formatting and trailing white space.
  • Uses the Files.lines method to stream the lines.
  • Presumes there are more than three lines in the file so add a merge function to take care of duplicate keys, if they should arise.
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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM