Writing from hashmap to txt file

I have hashMap Integer, String (K, V) and I want to write only string values ​​to a file (not a key integer), and I want to write only some 1st n entries (without a specific order) for the file, and not the whole map. I tried to look around a lot, but could not find a way to write the 1st n entries to the file. (There are examples where I can convert the value to an array of strings and then do it], but then it does not provide the correct format in which I want to write the file)

+4
source share
3 answers

It sounds like homework.

public static void main(String[] args) throws IOException { // first, let build your hashmap and populate it HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Value1"); map.put(2, "Value2"); map.put(3, "Value3"); map.put(4, "Value4"); map.put(5, "Value5"); // then, define how many records we want to print to the file int recordsToPrint = 3; FileWriter fstream; BufferedWriter out; // create your filewriter and bufferedreader fstream = new FileWriter("values.txt"); out = new BufferedWriter(fstream); // initialize the record count int count = 0; // create your iterator for your map Iterator<Entry<Integer, String>> it = map.entrySet().iterator(); // then use the iterator to loop through the map, stopping when we reach the // last record in the map or when we have printed enough records while (it.hasNext() && count < recordsToPrint) { // the key/value pair is stored here in pairs Map.Entry<Integer, String> pairs = it.next(); System.out.println("Value is " + pairs.getValue()); // since you only want the value, we only care about pairs.getValue(), which is written to out out.write(pairs.getValue() + "\n"); // increment the record count once we have printed to the file count++; } // lastly, close the file and end out.close(); } 
+8
source

Just a stream ...

Get an iterator for values. Iterations through them increase the counter. Exit when the counter reaches n records.

Another approach is to use

 for(int i=0, max=hashmap.size(); i<max, i<n; i++) { ... } 
0
source

Link: Java API

try it

  • Get a set of values ​​from the map. Read the reference to the Map object and find a method called values . Use this method
  • Iterate over the set of values ​​that you received in step 1. Enter some (of your choice) into the file. Format if desired when recording.
0
source

Source: https://habr.com/ru/post/1469278/


All Articles