Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing from hashmap to a txt file

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

like image 267
mag443 Avatar asked Feb 17 '23 04:02

mag443


1 Answers

This sounds like homework.

public static void main(String[] args) throws IOException {
    // first, let's 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();
}
like image 124
AWT Avatar answered Feb 24 '23 13:02

AWT