how to create a hash table in java - java

I have a csv file of 2 column. I`m trying to create a hash table for each dimension - only add a value if I haven't seen it before. I want to create 2 separate hash table for every column. columns contain string and numeric value. From the class definition i found containsKey(Object key) methoid Tests if the specified object is a key in this hashtable. i can explain a bit detail like my csv file may look like as below
New York, 50
Sydney, jessi
california, 10
New York, 10
so for column 1 New york came 2 in hash table i`d like to put key New York and value 2
can anyone help me how can i create a hash table like this way using java hashtable class, or maintain a separate array

Try this open source project on SourceForge called OpenCSV.
Then you could code something like this to read the CSV into your Map.
try {
CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(new File("/path/to/your/file.csv"))));
Map<String, String> result = new HashMap<String, String>();
for(String[] row : reader.readAll()) {
result.put(row[0], row[1]);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can read more on the OpenCSV documentation here.

Related

Apache Commons CSV Mapping not found

I am trying to read a CSV file with certain headers into a Java object using Apache Commons CSV. However, when I run the code, I get the following exeption:
Exception in thread "main" java.lang.IllegalArgumentException: Mapping for Color not found, expected one of [Color, Name, Price, House Cost, Rent, 1 House, 2 Houses, 3 Houses, 4 Houses, Hotel, Mortgage]
at org.apache.commons.csv.CSVRecord.get(CSVRecord.java:102)
at GameBoard.<init>(GameBoard.java:25)
at Game.main(Game.java:3)
Can someone explain where the exception is coming from? It appears to me that Apache Commons somehow is not matching my input to a column. Is there something wrong on my part or is something else broken? Here is my code snippet:
Reader in;
Iterable<CSVRecord> records = null;
try {
in = new FileReader(new File(Objects.requireNonNull(getClass().getClassLoader().getResource("Properties.csv")).getFile()));
records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
System.exit(1);
}
for (CSVRecord record :
records) {
spaces.add(new Property(
record.get("Color"),
record.get("Name"),
Integer.parseInt(record.get("Price")),
And here are my csv headers (sorry, one was cut off but that's not the point):
Thanks!
I had the same probem which only occurs if you reference the first column, all other column names are working. The problem is, that the UTF-8 representation prepends the following characters "0xEF,0xBB,0xBF" (see Wikipedia page). This seems to be a known problem for commons-csv but since this is application specific, it won't be fixed (CSVFormat.EXCEL.parse should handle byte order marks).
However, there is a documented workaround for this:
http://commons.apache.org/proper/commons-csv/user-guide.html#Handling_Byte_Order_Marks
I got the same weird exception. It actually said "Expecting one of ..." and then listed the field it said it could not find - just like in your case.
The reason was that I had set the wrong CSVFormat:
CSVFormat csvFormat = CSVFormat.newFormat(';');
This meant that my code was trying to separate fields on semi-colons in a file that actually had comma separators.
Once I used the DEFAULT CSVFormat, everything started to work.
CSVFormat csvFormat = CSVFormat.DEFAULT;
So the answer is that probably you must set CSVFormat correctly for your file.
Moving to spring boot version 2.6.7 from 2.4.5 brought about this error.. I had to convert each csvRecord to a map before assigning it to my POJO as follows.
for (CSVRecord csvRecord : csvRecords) {
Map<String, String> csvMap = csvRecord.toMap();
Model newModel = new Model();
model.setSomething(csvMap.get("your_item"));
}
I also got the same exception by giving a different name of header in CSV file like xyz, or trying to get the value by calling csvRecord.get("x_z")
I resolved my problem changing the header name xyz.
try {
fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
csvParser = new CSVParser(fileReader,
CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
CSVFormat csvFormat = CSVFormat.DEFAULT;
for (CSVRecord csvRecord : csvRecords) {
} catch (Exception e) {
System.out.println("Reading CSV Error!");
e.printStackTrace();
} finally {
try {
fileReader.close();
csvParser.close();
} catch (IOException e) {
System.out.println("Closing fileReader/csvParser Error!");
e.printStackTrace();
}
}

Java read .txt file with array and save

Ok this is quite a long one but I've looked everywhere and I'm still unsure on how to do it. This is a list of students information in the classroom layout. The program is used to let a child choose a seat but once they have chose it then it should have a status update so nobody else can take it.
Columns explained - (1)Student in number order (2)Male/Female (3)Window Seat/Aisle Seat (4)With/Without table (5)Forward Seat/Backward Seat (6) Ease of Access Seat
.txt file;
01 2 true false true false
02 2 false false true false
03 1 true false true true
04 2 false false true true
05 1 true true true false
I understand they don't totally make sense but it's just an example.
How do I get the program to read through each one of these rows using an array to store all this information? for child 1,2,3's seat etc. The .txt file represents exactly what kind of seat it is as explained above. Once the array has read through I want it to be able to save each row.
If you just want to read a file and store each line seperately in an array you can do the following. Note that it's not possible to create the array beforehand as you do not know how many lines you will get.
String[] result;
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path"))) {
while (reader.ready()) {
lines.add(reader.readLine());
}
} catch (IOException e) {
// proper error handling
}
result = lines.toArray(new String[lines.size()]);
Or if you want to be able to access the columns directly:
String[][] result;
ArrayList<String[]> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path"))) {
while (reader.ready()) {
lines.add(reader.readLine().split(" ");
}
} catch (IOException e) {
// proper error handling
}
result = lines.toArray(new String[lines.size()][]);
for(String[] lineTokens) {
String studendNumber = lineTokens[0];
boolean gender = Boolean.parseBoolean(lineTokens[1]);
...
}
let's say your file name is students.txt
all u need to do is read the data and store it into an array of strings to deeal with it later so her's the stuff :
BufferedReader in = new BufferedReader(new FileReader("students.txt"));
String[][] data = new String[][6];
int i = 0;
while(in.ready()){
data[i] = bf.readLine().split(" ");//use whatever is separating the data
i++;
}
If you just want to read a text file in java, have a look at this: Reading a plain text file in Java
A saving of each row won't be possibe, it's a file, not a database. So load the file, change the data as you like, save it.
You should also think about the format... may be use XML, JSON or CSV format to store the data. There are libs which do most of the job for you...
If you are planning parallel access to your program data (more than one program instance and users, only one datafile), a simple text file is the wrong solution for your needs.

Java: Using File & Buffered Reader to fill an Array

So, I have my first Java project due in my new course this Sunday. One of the (most important) things we need to do is to fill 2 arrays with information read from a file. My professor said to use a file and buffered reader to do this.
Unfortunately, I've never used either.
For the first array I need to: Create a String array with 15 elements, then Read the state search data from the data file and store each item into the array.
The filename is 'states.search.txt' and contains the following.
California
Texas
AK
California
Indiana
Missippi
Jacksonville
Okalahooma
Florida
Maine
Hawaii
Puerto_Rico
FL
New_York
Auburn
The 2nd array is a lot more involved, so I'll ask separately for that one.
All help is appreciated!
You can read lines from file follow:
public static void main(String args[]) {
try {
List<String> states = new ArrayList(15)<>; // ArrayList is superstructure over array
FileInputStream fstream = new FileInputStream("C:\\states.search.txt");
String state;
while ((state = br.readLine()) != null) {
states.add(state);
}
in.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
But you have to turn on your brain to do your home work, it's better for you.

Transposing arrays

I am using the following code to read in a CSV file:
String next[] = {};
List<String[]> dataArray = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
dataArray.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
This turns a CSV file into the array 'dataArray'. My application is for a dictionary type app - the input data's first column is a list of words, and the second column is the definitions of those words. Here is an example of the array loaded in:
Term 1, Definition 1
Term 2, Definition 2
Term 3, Definition 3
In order to access one of the strings in the array, I use the following code:
dataArray.get(rowNumber)[columnNumber]
However, I need to be able to generate a list of all the terms, so that they can be displayed for the dictionary application. As I understand it, accessing the columns by themselves is a much more lengthy process than accessing the rows (I come from a MATLAB background, where this would be simple).
It seems that in order to have ready access to any row of my input data, I would be better off transposing the data and reading it in that way; i.e.:
Term 1, Term 2, Term3
Definition 1, Definition 2, Definition 3
Of course, I could just provide a CSV file that is transposed in the first place - but Excel or OO Calc don't allow more than 256 rows, and my dictionary contains around 2000 terms.
Any of the following solutions would be welcomed:
A way to transpose an array once it has been read in
An alteration to the code posted above, such that it reads in data in the 'transposed' way
A simple way to read an entire column of an array as a whole
You would probably be better served by using a Map data structure (e.g. HashMap):
String next[] = {};
HashMap<String, String> dataMap = new HashMap<String, String>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
dataMap.put(next[0], next[1]);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
Then you can access the first column by
dataMap.keySet();
and the second column by
dataMap.values();
Note one assumption here: that the first column of your input data is all unique values (that is, there are not repeated values in the "Term" column).
To be able to access the keys (terms) as an array, you can simply do as follows:
String[] terms = new String[dataMap.keySet().size()];
terms = dataMap.keySet().toArray(terms);
If each row has two values, where the first one is the term and the second one is the definition, you could build a Map of it like this (Btw, this while loop does the exact same thing as your for loop):
String next[] = {};
Map<String, String> dataMap = new HashMap<String, String>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
while((next = reader.readNext()) != null) {
dataMap.put(next[0], next[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
Then you can get the definition from a term via:
String definition = dataMap.get(term);
or all definitions like this:
for (String term: dataMap.keySet()) {
String definition = dataMap.get(term);
}

how to combine elements from two text files and put them in a third file in java

I have two files Persons.txt and Hobby.txt.In the third file i want to put all the persons names and add each name some hobbies.i read the names from the persons file but i don't know how to add each persons different hobbies.
As a starter think about it this way.
Read the persons.txt then read the hobby.txt -- you know how to
Create a list of strings - How you want the third file to look like.
List<String> stringToWriteList = new ArrayList<String>();
add to the list the strings -- You probably want to loop the person.txt file for each person, then you need to define how you want to get the hoppy -- maybe randomly?
stringToWrite.add(person1 +", "+ hoppy1); // Depends on the hobby logic
Then just write the list of strings to the file
try {
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
for(String line : stringToWriteList ){
out.write(line);
out.newLine();
}
out.close();
} catch (IOException e) {
System.out.println("Exception ");
}
There are more technical ways to accomplish this, but the idea from this example is to new comers pick up one or two new things on how to write to a file -- easier to read\understand.

Categories