How to fetch the values from HashMap - java

I have a HashMap
HashMap<String, String> cntrlInfo = new HashMap<String, String>();
in this map some values are there I need to read the value one by one i want store the values in string.
for example {GBP,001,101,CHDP}
now I would like to store
String ccy=GBP; how i can assign the values in string

import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<String, String> cntrlInfo = new HashMap<String, String>();
cntrlInfo.put("A", "GBP");
cntrlInfo.put("B", "001");
cntrlInfo.put("C", "101");
cntrlInfo.put("D", "CHDP");
StringBuilder sb = new StringBuilder();
for (String val : cntrlInfo.values()) {
sb.append(val);
}
System.out.println("sb = " + sb);
String ccy = sb.substring(sb.indexOf("GBP"), sb.indexOf("GBP") + 3);
String foo = sb.substring(sb.indexOf("001"), sb.indexOf("001") + 3);
String bar = sb.substring(sb.indexOf("101"), sb.indexOf("101") + 3);
String f = sb.substring(sb.indexOf("CHDP"), sb.indexOf("CHDP") + 4);
System.out.println("ccy = " + ccy);
System.out.println("foo = " + foo);
System.out.println("bar = " + bar);
System.out.println("f = " + f);
}
}

Related

How do i change method from using HashMap to a normal String method

Someone, please assist to change the method 'getBabyNameFrequencies' in class 'Result' from using HarshMap to a normal String method as is in the main/feeder class 'Solution'
/*
* The function is expected to return a STRING.
* The function accepts the following parameters:
* 1. STRING names
* 2. STRING synonyms
*/
class Solution {
private Map<String, Integer> mp = new HashMap<>();
private Map<String, String> p = new HashMap<>();
public String[] getBabyNameFrequencies(String[] names, String[] synonyms) {
for (String e : names) {
int idx = e.indexOf("(");
String name = e.substring(0, idx);
int w = Integer.parseInt(e.substring(idx + 1, e.length() - 1));
mp.put(name, w);
p.put(name, name);
}
for (String e : synonyms) {
int idx = e.indexOf(",");
String name1 = e.substring(1, idx);
String name2 = e.substring(idx + 1, e.length() - 1);
if (!mp.containsKey(name1)) {
mp.put(name1, 0);
}
if (!mp.containsKey(name2)) {
mp.put(name2, 0);
}
p.put(name1, name1);
p.put(name2, name2);
}
for (String e : synonyms) {
int idx = e.indexOf(",");
String name1 = e.substring(1, idx);
String name2 = e.substring(idx + 1, e.length() - 1);
union(name1, name2);
}
List<String> t = new ArrayList<>();
for (Map.Entry<String, Integer> e : mp.entrySet()) {
String name = e.getKey();
if (Objects.equals(name, find(name))) {
t.add(name + "(" + e.getValue() + ")");
}
}
String[] res = new String[t.size()];
for (int i = 0; i < res.length; ++i) {
res[i] = t.get(i);
}
return res;
}
private String find(String x) {
if (!Objects.equals(p.get(x), x)) {
p.put(x, find(p.get(x)));
}
return p.get(x);
}
private void union(String a, String b) {
String pa = find(a), pb = find(b);
if (Objects.equals(pa, pb)) {
return;
}
if (pa.compareTo(pb) > 0) {
mp.put(pb, mp.getOrDefault(pb, 0) + mp.getOrDefault(pa, 0));
p.put(pa, pb);
} else {
mp.put(pa, mp.getOrDefault(pa, 0) + mp.getOrDefault(pb, 0));
p.put(pb, pa);
}
}
}
The Solution Class/ Feeder Class with the Main method.
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String names = bufferedReader.readLine();
String synonyms = bufferedReader.readLine();
String result = Result.getBabyNameFrequencies(names, synonyms);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}

How to convert string to json sequentially

public void addNewUser(MongoClient mdbClient, String newUserName, String newUserPassword, DBManagement.DBRole roles) {
System.out.println("inside addNEw User method");
Map<String, String> user = new LinkedHashMap<String, String>();
user.put("createUser", newUserName);
user.put("pwd", newUserPassword);
List<Map<String, String>> listOfRoles = new ArrayList<Map<String, String>>();
Map<String, String> role1 = new LinkedHashMap<String, String>();
role1.put("role",roles.getRole());
role1.put("db", roles.getDb());
listOfRoles.add(role1);
user.put("roles", listOfRoles.toString());
System.out.println("MAP: " + user);
try{
String json = new ObjectMapper().writeValueAsString(user);
/*String json = new ObjectMapper().convertValue(user);*/
System.out.println(json);
//String jsonCommand = "{ createUser: \" + newUserName +"/" + " ," + "pwd: /" + newUserPassword + "/" + " ," + "roles : [" + roles_str + "]}" ;
String jsonCommand = json;
System.out.println("createUserString-->"+jsonCommand);
Document command = new Document(Document.parse(jsonCommand));
Document collStatsResults = mdbClient.getDatabase("admin").runCommand(command);
System.out.println(collStatsResults.toJson());
} catch(Exception e) {
System.out.println("Error " + e);
}
}
I am getting output string as -{"createUser":"demoUser2","pwd":"password","roles":"[{role=dbOwner, db=udata}]"}
Expected output- {"createUser":"demoUser2","pwd":"password","roles":[{"role":"dbOwner", "db":"udata"}]}
Firstly i used JSONObject() but it doesnt care about the json sequence ,so i tried with linkedhashMap but facing array conversion issue..can anyone help.Or is there any other way to generate json sequentially.

Rename filenames list with another list's filenames with java

import java.io.*;
public class Main {
public static void main(String[] args) {
// change file names in 'Directory':
String absolutePath = "/storage/emulated/0/Gadm";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
int i = 0;
for(File file:filesInDir) {
i++;
String[] iso = {
"AFG",
"XAD",
"ALA",
"ZWE"};
String[] country = {
"Afghanistan",
"Akrotiri and Dhekelia",
"Åland",
"Zimbabwe"};
String name = file.getName();
String newName = name.replace(iso[i],country[i]);
String newPath = absolutePath + "/" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " has been changed to " + newName);
}
}
}
I have a directory named Gadm It contains a list of files named as followed with countries' iso code for example iso.kmz I would rename all the filnames with its correspondent country name to become country.kmz
iso names stored in an array and also country names and in the correct order.
I tried this code above but it doesn't work
Instead of using two arrays, I would use a single HashMap where the keys are the country ISO codes and the value is the associated country name. Like:
String absolutePath = "/storage/emulated/0/Gadm/";
HashMap<String, String> countryCodes = new HashMap<>();
countryCodes.put("AFG","Afghanistan");
countryCodes.put("XAD","Akrotiri and Dhekelia");
countryCodes.put("ALA","Åland");
countryCodes.put("ZWE","Zimbabwe");
for(Map.Entry<String, String> entry : countryCodes.entrySet()) {
File file = new File(absolutePath + entry.getKey());
if (file.renameTo(new File(absolutePath + entry.getValue()))) {
System.out.println("Successfully renamed " + entry.getKey() + " to " + entry.getValue());
} else {
System.out.println("Failed to rename " + entry.getKey() + " to " + entry.getValue() +
". Please make sure filepath exists: " + absolutePath + entry.getKey());
}
}
AS alternative, you can use Path isntead of File:
public static void rename(Path source) throws IOException {
Map<String, String> countries = countries.get();
Files.list(source)
.filter(path -> Files.isRegularFile(path))
.filter(path -> countries.containsKey(getFileName.apply(path)))
.forEach(path -> {
try {
Files.move(path, source.resolve(countries.get(getFileName.apply(path)) + getFileExt.apply(path)));
} catch(IOException e) {
e.printStackTrace();
}
});
}
private static final Function<Path, String> getFileName = path -> {
String fileName = path.getFileName().toString();
return fileName.substring(0, fileName.lastIndexOf('.')).toUpperCase();
};
private static final Function<Path, String> getFileExt = path -> {
String fileName = path.getFileName().toString();
return fileName.substring(fileName.lastIndexOf('.'));
};
private static Supplier<Map<String, String>> countries = () -> {
Map<String, String> map = new HashMap<>();
map.put("AFG", "Afghanistan");
map.put("XAD", "Akrotiri and Dhekelia");
map.put("ALA", "Åland");
map.put("ZWE", "Zimbabwe");
return Collections.unmodifiableMap(map);
};
Client code is: rename(Paths.get("h:/gadm"))

how to connect and insert map keys and values into derby database?

I have a java program and it produces the output as follows :
termname :docname : termcount
Forexample termname is hello and docname is :2 and termcount is :4
hello:doc1:4
.....
......
I stored all the values in a map. here is the following program
public class tuple {
public static void main(String[]args) throws FileNotFoundException, UnsupportedEncodingException, SQLException, ClassNotFoundException, Exception{
File file2 = new File("D:\\logs\\tuple.txt");
PrintWriter tupled = new PrintWriter(file2, "UTF-8");
List<Map<String, Integer>> list = new ArrayList<>();
Map<String, Integer>map= new HashMap<>();;
String word;
//Iterate over documents
for (int i = 1; i <= 2; i++) {
//map = new HashMap<>();
Scanner tdsc = new Scanner(new File("D:\\logs\\AfterStem" + i + ".txt"));
//Iterate over words
while (tdsc.hasNext()) {
word = tdsc.next();
final Integer freq = map.get(word);
if (freq == null) {
map.put(word, 1);
} else {
map.put(word, map.get(word) + 1);
}
}
list.add(map);
}
// tupled.println(list);
//tupled.close();
//Print result
int documentNumber = 0;
for (Map<String, Integer> document : list) {
for (Map.Entry<String, Integer> entry : document.entrySet()) {
documentNumber++;
//System.out.println(entry.getKey() + ":doc"+documentNumber+":" + entry.getValue());
tupled.print(entry.getKey());
tupled.print(":doc:");
tupled.print(Integer.toString(documentNumber));
tupled.print(",");
tupled.println(entry.getValue());
}
//documentNumber++;
}
tupled.close();
Now I want to store this values into derby database of neatbeans.
How I would be able to do that ?

Parsing a CSV file into HashMap stores a null value

I am trying to read off a csv file and store the data into a hash map.
I am able to correctly add the key but when adding the value, it is adding null for every single one. I am not sure why. Here is my code:
EDITED CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class ExampleActivity {
public static HashMap<String, String> hm = new HashMap<String, String>();
public static void readCountry() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("countries.csv"));
String line;
HashMap<String, String> hm = new HashMap<String, String>();
while ((line = reader.readLine()) != null) {
String str[] = line.split(",");
if (str.length > 1) {
System.out.println("Data 0: " + str[0]);
System.out.println("Data 1: " + str[1]);
hm.put(str[0].trim(), str[1]);
}
}
//System.out.println(hm);
}
public static void main(String[] args) throws IOException {
readCountry();
Scanner in = new Scanner(System.in);
String l = null;
System.out.println("Please enter a three letter country:");
l = in.nextLine();
l = l.trim();
// System.out.println("Country Code: " + l + "\nCountry Name: " +
// hm.get(l) );
if (hm.containsKey(l)) {
System.out.println("Country Code: " + l + "\nCountry Name: "
+ hm.get(l));
} else {
System.out.println("Missing key for " + l);
}
}
}
Here is a sample of the CSV file
AFG,Afghanistan
AGO,Angola
AIA,Anguilla
...
Here is a screenshot of the output:
Comment out method local declaration of hashmap and it should work fine. Make change to code as below:
public static void readCountry() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("d:/countries1.csv"));
String line;
// HashMap<String, String> hm = new HashMap<String, String>(); Remove this line
Try this:
while((line = reader.readLine()) != null){
String str[] = line.split(",");
if (str.size() > 1){
System.out.println("Data 0: " + str[0]);
System.out.println("Data 1: " + str[1]);
hm.put(str[0], str[1]);
}
}
Your for loop is unecessary
Also look at Dark Knight's answer for your null values issue
EDIT
Can you add this to your code and see what it does:
if (hm.containsKey(l)
System.out.println("Country Code: " + l + "\nCountry Name: " + hm.get(l) );
else
System.out.println("Missing key for " + l);
System.out.println("Printing hashmap");
for(Entry<String, String> entry : hm.entrySet()) {
{
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
EDIT2
hm.put(str[0].trim(), str[1]);
And the next bit
Scanner in = new Scanner(System.in);
String l;
System.out.println("Please enter a three letter country:");
l = in.nextLine();
l = l.trim();
Using the Stream API you could start with following snippet.
Path path = Paths.get("countries.txt");
Map<String, String> countries = Files.lines(path, StandardCharsets.UTF_8)
.filter((String l) -> !l.isEmpty())
.map((Object t) -> ((String) t).split(",", 2))
.collect(toMap((String[] l) -> l[0],
(String[] l) -> l.length > 1 ? l[1] : ""));
System.out.println("countries = " + countries);
output
countries = {AFG=Afghanistan, AIA=Anguilla, AGO=Angola}
The snippet filter out empty lines and for lines without a , the value is assigned as an empty string.
edit Your amended readCountry would look like
public static void readCountry() throws IOException {
Path path = Paths.get("countries.txt");
Map<String, String> hm = Files.lines(path, StandardCharsets.UTF_8)
.filter((String l) -> !l.isEmpty() && l.contains(","))
.map((Object t) -> ((String) t).split(",", 2))
.peek((String[] l) ->
System.out.printf("Data 0: %s%nData 1: %s%n", l[0], l[1]))
.collect(toMap((String[] l) -> l[0],
(String[] l) -> l[1]));
}
it store the key-value pairs in hm and produce as output
Data 0: AFG
Data 1: Afghanistan
Data 0: AGO
Data 1: Angola
Data 0: AIA
Data 1: Anguilla

Categories