I'm attempting to parse a CSV file into a HashMap. The CSV file contains name, email and age.
I've attempted it below but haven't had any luck progressing with it - beginner to Java
public class Extract {
public HashMap<String, Map<String, Integer>> readFile(String filename) {
HashMap<String, Map<String, Integer>> people = new HashMap<>();
try {
Scanner in = new Scanner(new File(filename));
String line;
while(in.hasNext()) {
line = in.nextLine();
String[] keyValue = line.split(",");
people.put(keyValue[0], keyValue[2], keyValue[3]);
}
in.close();
}
catch(Exception e) {
e.printStackTrace();
}
return people;
}
}
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
Extract e = new Extract();
String peopleFile = ("relationships.csv");
HashMap<String, String> person1 = e.readFile(peopleFile);
person1.get("Bob");
}
}
So here is the code as it should suit you. Try to understand what happens here. It seems that you're still struggling a little when it comes to Maps and how to use them properly.
public class Extract {
public HashMap<String, HashMap<String, String>> readFile(String filename) {
HashMap<String, HashMap<String, String>> people = new HashMap<>();
HashMap<String, String> metaData = new HashMap<>();
try {
Scanner in = new Scanner(new File(filename));
String line;
while(in.hasNext()) {
line = in.nextLine();
String[] keyValue = line.split(",");
// 1st put email address and age in the inner Map
metaData = new HashMap<>();
metaData.put("email", keyValue[1]);
metaData.put("age", keyValue[2]);
// 2nd put the inner Map into the outer Map, referenced by the person's name
people.put(keyValue[0], metaData);
}
in.close();
}
catch(Exception e) {
e.printStackTrace();
}
return people;
}
}
public class Main {
public static void main(String[] args) {
Extract e = new Extract();
String peopleFile = ("relationships.csv");
HashMap<String, HashMap<String, String>> person1 = e.readFile(peopleFile);
// 1st: get the inner Map of Bob
// If you use the get()-method, you tell the outer Map to hand you the inner Map of Bob.
HashMap<String, String> metaData = person1.get("Bob");
// 2nd: get the metaData off the inner Map
String email = metaData.get("email");
Integer age = Integer.valueOf(metaData.get("age"));
}
}
Related
All I get is an address of the hashmap, filewriter doesn't work, I've tried everything: scanner, bufferedwriter, re-writing the write() method.
public class hmapTest implements java.io.Serializable {
public static void main(String[] args) {
HashMap<Integer, String> hmap3 = new HashMap<Integer, String>();
// add elements to hashmap
hmap3.put(1, "to");
hmap3.put(2, "in");
hmap3.put(3, "at");
hmap3.put(4, "on");
hmap3.put(5, "under");
try {
FileOutputStream fos = new FileOutputStream("hashser.txt");
ObjectOutputStream ous = new ObjectOutputStream(fos);
ous.writeObject(hmap3);
ous.close();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Output:
’’loadFactorI etc
If you just need an arbitary human readable form you could do something like this:
class Main {
public static void main(String[] args) throws FileNotFoundException {
HashMap<Integer, String> hmap = new HashMap<>();
hmap.put(1, "to");
hmap.put(2, "in");
hmap.put(3, "at");
hmap.put(4, "on");
hmap.put(5, "under");
try (XMLEncoder stream = new XMLEncoder(new BufferedOutputStream(System.out))) {
stream.writeObject(hmap);
}
}
}
Yet, if it has to be CSV, you have to use a third party library (e.g. https://poi.apache.org/) , or implement it on your own. Also, if your data, is just a list of continues integers mapping to values, consider using a List instead of a HashMap.
I'm trying to parse this JSON using gson:
{"hvs1":{"16191":[["TestFile3","C",["A"]],["TestFile3","-",["1G","1A"]]],"16193":[["TestFile3","C",["G"]]]},"hvs2":{"25":[["TestFile3","-",["1A"]]]},"outros":{"16423":[["TestFile3","A",["T"]]]}}
Into this object
public class Results {
private String regiaoAfetada;
private String posicaoReferencia;
private String nomeDoArquivo;
private String baseAlteradaReferencia;
private List<String> mutacaoEncontrada;
//get and set
}
And my test class to try to achive this, but I'm getting a error.
public class JsonTeste {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
Type type = new TypeToken<TreeMap<String, TreeMap>>() {
}.getType();
TreeMap<String, TreeMap<String, List<List<List<String>>>>> map = gson.fromJson(reader, type);
List<Results> listaMutacoes = new ArrayList<Results>();
for (Entry<String, TreeMap<String, List<List<List<String>>>>> regioesMap : map.entrySet()) {
TreeMap<String, List<List<List<String>>>> regiaoUm = regioesMap.getValue();
for (Entry<String, List<List<List<String>>>> regiaoUmResult : regiaoUm.entrySet()) {
List<List<List<String>>> resultados = regiaoUmResult.getValue();
for (List<List<String>> list : resultados) {
Results resultado = new Results();
resultado.setRegiaoAfetada(regioesMap.getKey());
resultado.setPosicaoReferencia(regiaoUmResult.getKey());
resultado.setNomeDoArquivo(list.get(0).toString());
resultado.setBaseAlteradaReferencia(list.get(1).toString());
resultado.setMutacaoEncontrada(list.get(2));
listaMutacoes.add(resultado);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem is when I try to parse this part
[
"TestFile3",
"-",
[
"1G",
"1A"
]
]
Because I have two Strings and a Array inside, so the problem Is when I try to place "TestFile3" into setNomeDoArquivo, but even if I comment this line, i get the same error in the second line.
resultado.setNomeDoArquivo(list.get(0).toString());
resultado.setBaseAlteradaReferencia(list.get(1).toString());
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List
Can you guys help me?
The List resultados is of List<string> or List<List<String>>.When you get the item of resultados it can be one of them. So to generalized declare it as List<List<Object>>
Try The below Code :
Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
Type type = new TypeToken<TreeMap<String, TreeMap>>() {
}.getType();
TreeMap<String, TreeMap<String, List<List<Object>>>> map = gson.fromJson(reader, type);
List<Results> listaMutacoes = new ArrayList<>();
for (Map.Entry<String, TreeMap<String, List<List<Object>>>> regioesMap : map.entrySet()) {
TreeMap<String, List<List<Object>>> regiaoUm = regioesMap.getValue();
for (Map.Entry<String, List<List<Object>>> regiaoUmResult : regiaoUm.entrySet()) {
List<List<Object>> resultados = regiaoUmResult.getValue();
for (List<Object> list : resultados) {
System.out.println(list);
Results resultado = new Results();
resultado.setRegiaoAfetada(regioesMap.getKey());
resultado.setPosicaoReferencia(regiaoUmResult.getKey());
resultado.setNomeDoArquivo((String) list.get(0));
resultado.setBaseAlteradaReferencia((String) list.get(1));
resultado.setMutacaoEncontrada((List<String>) list.get(2));
listaMutacoes.add(resultado);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Following is my code that returning false even if the key exists:
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class SequenceNumber {
public static int getSequenceNumber (String TcOrderId){
// Create a hash map to set key values pair.
Map<String, Integer> map = new HashMap<String, Integer>();
int i= 1;
// check if hashmap contains the key.
System.out.println("key present " +map.containsKey(TcOrderId));
if (map.containsKey(TcOrderId))
{
//Key Present
System.out.println("Inside IF ");
int value = map.get(TcOrderId);
System.out.println("value from the key " + value);
map.remove(value);
map.put(TcOrderId, value+1);
return map.get(TcOrderId);
}
else
{
//Key Not present
System.out.println("INSIDE ELSE ");
map.put(TcOrderId, i);
System.out.println("map "+ map);
return map.get(TcOrderId);
}
}
public static void main(String[] args) throws IOException {
String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = getSequenceNumber(sCurrentLine);
System.out.println("seqvalue "+seqvalue);
}
}
}
}
Input data in the file:
1233
1233
1234
The result should be
1
2
1
But everytime its going in the else loop and the result is
1
1
1
I am trying to use HASHMAP as I am creating my own index.
In your CODE everytime you call getSequenceNumber function - you create new HashMap. I believe this is not something you want.
To avoid that - you can simply move Map<String, Integer> map = new HashMap<String, Integer>(); into the body of class. Since the function getSequenceNumber is a static function - you will need to make the variable static. Hope this helps.
Snippet:
public class SequenceNumber {
// PUT STATIC VARIABLE HERE:
static Map<String, Integer> map = new HashMap<String, Integer>();
public static int getSequenceNumber (String TcOrderId){
// Create a hash map to set key values pair.
// (REMOVE) Map<String, Integer> map = new HashMap<String, Integer>();**
int i= 1;
// check if hashmap contains the key.
...
}
...
}
Another alternative
(perhaps better) would be to avoid static functions and variables and create an instance of SequenceNumber object. That way you could keep a couple of different instance numbers separately.
Simple snippet:
public class SequenceNumber {
// Your hashmap here:
Map<String, Integer> map = new HashMap<String, Integer>();
public int getSequenceNumber (String TcOrderId) {
// ...
}
public static void main(String[] args) throws IOException {
// Instance of SequenceNumber object:
SequenceNumber sequenceNumber = new SequenceNumber();
String sCurrentLine;
BufferedReader br = null;
// ...
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = sequenceNumber.getSequenceNumber(sCurrentLine);
System.out.println("seqvalue "+seqvalue);
}
// ...
}
}
Something like this should work. Haven't tried running it though.
public class SequenceNumber {
public static int getSequenceNumber (String TcOrderId, Map<String, Integer> map){
if(!map.contains(TcOrderId)){
map.put(TcOrderId, 0);
}
map.put(TcOrderId, map.get(TcOrderId)+1);
return map.get(TcOrderId);
}
public static void main(String[] args) throws IOException {
String sCurrentLine;
BufferedReader br = null;
Map<String, Integer> map = new HashMap<String, Integer>();
try {
br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = getSequenceNumber(sCurrentLine, map);
System.out.println("seqvalue "+seqvalue);
}
}
This is my first question here so please bear with me. I have a text file that looks like something like this;
userId,itemId,rating
1,101,2.5
4,103,3.0
1,103,3.0
6,104,3.5
2,101,3.0
4,106,4.5
2,103,1.5
5,102,4.0
2,105,3.5
7,106,3.0
3,101,2.5
3,102,3.0
What I'am trying to accomplish is to read the file line per line and seperated each value. After that is done place all unique userIds in the key section of this map; Map<Integer, Map<Integer, Double>>. And place the itemIds with the rating in the second map corresponding to the key of the first map. Can you still follow me?? Here is the code I produced so far with not the outcome I want.
This is my User class:
package com.example;
import java.util.HashMap;
import java.util.Map;
public class User {
private int mUserId;
private Map<Integer, Double> mRatedItems;
public User(int userId) {
mUserId = userId;
mRatedItems = new HashMap<>();
}
public int getUserId() {
return mUserId;
}
public void setUserId(int userId) {
mUserId = userId;
}
public Map<Integer, Double> getRatedItems() {
return mRatedItems;
}
public void addRatedItems(int itemId, double rating) {
mRatedItems.put(itemId, rating);
}
}
This is the file I need to modify:
package com.example;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class TextFile {
List<User> mUserIdList;
private User mUser;
public Map<Integer, Map<Integer, Double>> readFile(String fileName) {
mUserIdList = new ArrayList<>();
Map<Integer, Map<Integer, Double>> userItemData = new HashMap<>();
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))
) {
String line;
while ((line = reader.readLine()) != null) {
String[] args = line.split(",");
int userId = Integer.parseInt(args[0]);
int itemId = Integer.parseInt(args[1]);
double rating = Double.parseDouble(args[2]);
if (!mUserIdList.contains(userId)) {
mUser = new User(userId);
mUserIdList.add(mUser);
}
if (!mUserIdList.isEmpty()) {
addItemRatings(userId, itemId, rating);
}
if (!checkDuplicates()) {
userItemData.put(mUser.getUserId(), mUser.getRatedItems());
}
}
} catch (IOException e) {
System.out.printf("Problem loading: %s %n", fileName);
e.printStackTrace();
}
return userItemData;
}
private boolean checkDuplicates() {
Set<Integer> set = new HashSet<>();
for (User user : mUserIdList) {
if (!set.add(user.getUserId())) {
return true;
}
}
return false;
}
public void addItemRatings(int userId, int itemId, double rating) {
for (User user : mUserIdList) {
if (user.getUserId() == userId) {
user.addRatedItems(itemId, rating);
}
}
}
public int showTextLines(String fileName) {
int textLines = 0;
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))
) {
while (reader.readLine() != null) {
textLines++;
}
reader.close();
} catch (IOException e) {
System.out.printf("Problem showing total lines from: %s %n", fileName);
e.printStackTrace();
}
return textLines;
}
}
This is my main class:
package com.example;
import java.util.Map;
public class Main {
public static void main(String[] args) {
TextFile textFile = new TextFile();
String location = "D:\\IdeaProjects\\KMeans\\src\\com\\quincy\\userItem1.data";
Map<Integer, Map<Integer, Double>> readFile = textFile.readFile(location);
int textLines = textFile.showTextLines(location);
System.out.printf("File: %s %n", readFile);
System.out.printf("Number of lines in file: %s %n", textLines);
}
}
And my output is:
File: {1={101=2.5, 103=3.0}, 4={103=3.0, 106=4.5}}
Number of lines in file: 12
My code is only adding the first two userIds with their corresponding itemIds and rating. Can somebody please explain to me what I' am doing wrong?? And maybe show how I can improve this code to work properly??
Thanks in advance.
The problem is in your checkDuplicates() method. I don't know what exactly you're trying to achieve on that function but if you want to check for duplications. then, I suggest you just use the function containsKey() like this.
if (!userItemData.containsKey(mUser.getUserId())) {
userItemData.put(mUser.getUserId(), mUser.getRatedItems());
}
Question : I want to change the hard coding json file path. The path will be from detailsListHM but I dont know how to do it.
Here is my main program
public class Program {
// hard coding json file path
private static final String filePath = "C:/appSession.json";
public static void main(String[] args)
{
taskManager();
}
public static void taskManager()
{
detailsHM = jsonParser(filePath);
}
public static HashMap<String, String> jsonParser(String jsonFilePath)
{
HashMap<String, String> detailsHM = new HashMap<String, String>();
String refGene = "";
try {
// read the json file
FileReader reader = new FileReader(filePath);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
Here is another class called CustomConfiguration
public class CustomConfiguration {
private static HashMap<String, String> detailsListHM =new HashMap<String,String>();
public static void readConfig(String a) {
//read from config.properties file
try {
String result = "";
Properties properties = new Properties();
String propFileName = a;
InputStream inputStream = new FileInputStream(propFileName);
properties.load(inputStream);
// get the property value and print it out
String lofreqPath = properties.getProperty("lofreqPath");
String bamFilePath = properties.getProperty("bamFilePath");
String bamFilePath2 = properties.getProperty("bamFilePath2");
String resultPath = properties.getProperty("resultPath");
String refGenPath = properties.getProperty("refGenPath");
String filePath = properties.getProperty("filePath");
Set keySet = properties.keySet();
List keyList = new ArrayList(keySet);
Collections.sort(keyList);
Iterator itr = keyList.iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
String value = properties.getProperty(key.toString());
detailsListHM.put(key, value);
}
} catch (IOException ex) {
System.err.println("CustomConfiguration - readConfig():" + ex.getMessage());
}
}
public static HashMap<String, String> getConfigHM() {
return detailsListHM;
}
Add a new property call "json-filepath" and read like
String filePath = properties.getProperty("json-filepath");
So the end user can change the json file path even during the runtime.
you can pass the filePath parameter by using the main parameters.
public static void main(String[] args) {
String filePath = null;
if(args.length > 0) {
filePath = args[0];
}
}
And invoke your main class like this:
java Program C:/appSession.json