There is a task: you need to organize work with an associative array in java using Map. Namely, there are 2 files with entries: a key and a value type. The key needs to be output to 3 files, the result on keys 2 and 5. I figured out how to create a map, but how to read data from files, exactly so that the key value is written first, and after reading the file, the next one is written in the reverse order. After all, when declaring a map, the type of key and the contents in it are specified, but first this number and letter, and then in the second file the letter, the number are the files and data:

1.txt

 1 a 2 v 3 f 4 g 

2.txt

 k 6 b 3 n 5 m 7 

result.txt

2 5

 package task; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class task1_collections { private InputStream input; private OutputStream out; String line; Map<int, String> map1 = new HashMap<int, String>(); Map<String, int> map1 = new HashMap<String, int>(); } 

Still eclipses swears and does not allow to set the whole and. but only the string and the string how to count from the files in the map and did not figure out

  • file is set to column - Oleg

2 answers 2

I got this solution:

 Map<Integer, String> map = new HashMap<>(); Files .lines(Paths.get("1.txt")) .map(str -> str.split(" ")) .forEach(value -> map.put(Integer.valueOf(value[0]), value[1])); Files .lines(Paths.get("2.txt")) .map(str -> str.split(" ")) .forEach(value -> map.put(Integer.valueOf(value[1]), value[0])); 
  • and where are the values ​​actually recorded in the map after a show or as a submap? - Oleg
  • and what are the Files? - Oleg
  • HashMap <Integer, String> map <is a hash table containing a key of type Integer and a value of type String. In this data structure, the values ​​are not ordered. Each line from the file is broken into two lines, which are then reduced to the desired type and written to the map. java.nio.file.Files is a class in which there is a static method lines - Artem Konovalov

Specifically for questions.

1 - you cannot use primitives ( int ), you need to use a wrapper (boxing) over it ( Integer ).

2 - it is impossible to read from a file just like that in a map. If this file was obtained by realizing, then it is possible, otherwise it is read line by line. Sample code:

  BufferedReader br = null; Map<Integer, String> map = new HashMap<>(); try { String sCurrentLine; br = new BufferedReader(new FileReader("1.txt")); while ((sCurrentLine = br.readLine()) != null) map.put(Integer.valueOf(sCurrentLine), br.readLine); } catch (Throwable e) { } finally { try { if (br != null) br.close(); } catch (Throwable ee) { } } 
  • For the second file, repeat the operation with a record in the same map or use the second one already? - Oleg
  • judging by your logic - the second. - pavel