I'm trying to put some Strings to a HashMap, but they wont add.
My code looks like this and I can't seem to understand why they won't add. Can someone help me and give me an explanation to what I'm doing wrong?
HashMap <String, String> akro = new HashMap <String, String>();
public void lesFil() {
try {
BufferedReader br = new BufferedReader(new FileReader("akronymer.txt"));
String line;
while((line = br.readLine()) != null) {
if(!line.contains(" ")) {
continue;
}
String[] linje = line.split("\\s+", 2);
String akronym = linje[0];
String betydning = linje[1];
// System.out.println(a + " || " + b);
akro.put(akronym, betydning);
}
} catch(Exception e) {
System.out.println("Feilen som ble fanget opp: " + e);
}
}
When I'm removing "//", both akronym and betydning prints out fine.
I tried to add this method to test the HashMap but nothing prints out and the size = 0
public void skrivUt() {
for(Map.Entry <String, String> entry : akro.entrySet()) {
System.out.print("Key: " + entry.getKey());
System.out.println(", Value: " + entry.getValue());
}
System.out.println("Antall akronymer: " + akro.size());
}
Part of the file I'm reading from(txt file):
...
CS Chip Select
CS Clear to Send
CS Code Segment
C/S Client/Server
...
Remember that a Map in Java maps one key to one value. In the sample data you provide, it seems that you have multiple values ("Chip Select", "Clear to Send", "Code Segment") for one key ("CS").
You can solve this by either picking a structure other than a Map, changing what you want to store, or changing the value of the Map to a List<String>.
For example:
List<String> values = akro.get(akronym);
if(values == null) {
values = new LinkedList<String>();
akro.put(akronym, values);
}
values.add(betydning);
Related
I am trying to restrict the results of my BabelNet query to a specific (Babel)domain. To do that, I'm trying to find out a way to compare the synsets' domains with the domain I need (Geographical). However, I'm having trouble getting the right output, since although the 2 strings match, it still gives me the wrong output. I'm surely doing something wrong here, but I'm out of ideas.
After many trials, the following code was the one that gave me the nearest result to the desired output:
public class GeoRestrict {
public static void main(String[] args) throws IOException {
String file = "/path/to/file/testdata.txt";
BabelNet bn = BabelNet.getInstance();
BufferedReader br = new BufferedReader(new FileReader(file));
String word = null;
while ((word = br.readLine()) != null) {
BabelNetQuery query = new BabelNetQuery.Builder(word)
.build();
List<BabelSynset> wordSynset = bn.getSynsets(query);
for (BabelSynset synset : wordSynset) {
BabelSynsetID id = synset.getID();
System.out.println("\n" + "Synset ID for " + word.toUpperCase() + " is: " + id);
HashMap<Domain, Double> domains = synset.getDomains();
Set<Domain> keys = domains.keySet();
String keyString = domains.keySet().toString();
List<String> categories = synset.getDomains().keySet().stream()
.map(domain -> ((BabelDomain) domain).getDomainString())
.collect(Collectors.toList());
for (String category : categories) {
if(keyString.equals(category)) {
System.out.println("The word " + word + " has the domain " + category);
} else {
System.out.println("Nada! " + category);
}
}
}
}
br.close();
}
}
The output looks like this:
Synset ID for TURIN is: bn:00077665n
Nada! Geography and places
Any ideas on how to solve this issue?
I found my own error. For the sake of completeness I'm posting it.
The BabelDomain needs to be declared and specified (before the while-loop), like this:
BabelDomain domain = BabelDomain.GEOGRAPHY_AND_PLACES;
I have a set of strings like this
A_2007-04, A_2007-09, A_Agent, A_Daily, A_Execute, A_Exec, B_Action, B_HealthCheck
I want output as:
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
Key = B, Value = [Action,HealthCheck]
I'm using HashMap to do this
pckg:{A,B}
count:total no of strings
reports:set of strings
Logic I used is nested loop:
for (String l : reports[i]) {
for (String r : pckg) {
String[] g = l.split("_");
if (g[0].equalsIgnoreCase(r)) {
report.add(g[1]);
dirFiles.put(g[0], report);
} else {
break;
}
}
}
I'm getting output as
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
How to get second key?
Can someone suggest logic for this?
Assuming that you use Java 8, it can be done using computeIfAbsent to initialize the List of values when it is a new key as next:
List<String> tokens = Arrays.asList(
"A_2007-04", "A_2007-09", "A_Agent", "A_Daily", "A_Execute",
"A_Exec", "P_Action", "P_HealthCheck"
);
Map<String, List<String>> map = new HashMap<>();
for (String token : tokens) {
String[] g = token.split("_");
map.computeIfAbsent(g[0], key -> new ArrayList<>()).add(g[1]);
}
In terms of raw code this should do what I think you are trying to achieve:
// Create a collection of String any way you like, but for testing
// I've simply split a flat string into an array.
String flatString = "A_2007-04,A_2007-09,A_Agent,A_Daily,A_Execute,A_Exec,"
+ "P_Action,P_HealthCheck";
String[] reports = flatString.split(",");
Map<String, List<String>> mapFromReportKeyToValues = new HashMap<>();
for (String report : reports) {
int underscoreIndex = report.indexOf("_");
String key = report.substring(0, underscoreIndex);
String newValue = report.substring(underscoreIndex + 1);
List<String> existingValues = mapFromReportKeyToValues.get(key);
if (existingValues == null) {
// This key hasn't been seen before, so create a new list
// to contain values which belong under this key.
existingValues = new ArrayList<>();
mapFromReportKeyToValues.put(key, existingValues);
}
existingValues.add(newValue);
}
System.out.println("Generated map:\n" + mapFromReportKeyToValues);
Though I recommend tidying it up and organising it into a method or methods as fits your project code.
Doing this with Map<String, ArrayList<String>> will be another good approach I think:
String reports[] = {"A_2007-04", "A_2007-09", "A_Agent", "A_Daily",
"A_Execute", "A_Exec", "P_Action", "P_HealthCheck"};
Map<String, ArrayList<String>> map = new HashMap<>();
for (String rep : reports) {
String s[] = rep.split("_");
String prefix = s[0], suffix = s[1];
ArrayList<String> list = new ArrayList<>();
if (map.containsKey(prefix)) {
list = map.get(prefix);
}
list.add(suffix);
map.put(prefix, list);
}
// Print
for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> valueList = entry.getValue();
System.out.println(key + " " + valueList);
}
for (String l : reports[i]) {
String[] g = l.split("_");
for (String r : pckg) {
if (g[0].equalsIgnoreCase(r)) {
report = dirFiles.get(g[0]);
if(report == null){ report = new ArrayList<String>(); } //create new report
report.add(g[1]);
dirFiles.put(g[0], report);
}
}
}
Removed the else part of the if condition. You are using break there which exits the inner loop and you never get to evaluate the keys beyond first key.
Added checking for existing values. As suggested by Orin2005.
Also I have moved the statement String[] g = l.split("_"); outside inner loop so that it doesn't get executed multiple times.
In my query I can't use hibernate and I need to generate a String as follows:
I have Map<String, String> restrictions instance with 3 keys (id, name and value) and I want to get the entry (String).
if (restrictions.get("id") != null && restrictions.get("name") == null && restrictions.get("value") == null){
return "ID = " + restrictions.get("id");
} else if (restrictions.get("id") != null && restrictions.get("name") != null && restrictions.get("value" != null)){
return "ID = " + restrictions.get("id") + " and Name = " + restrictions.get("name");
}
And so forth...
Explicitly writting the if-else clauses is very unflexible and hardly maintainable way. Any ideas?
Use java.util.StringJoiner:
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
public class SOPlayground {
public static void main(String[] args) throws Exception {
Map<String, String> restrictions = new HashMap<>();
restrictions.put("id", "foo");
restrictions.put("name", "bar");
restrictions.put("not set", null);
StringJoiner joiner = new StringJoiner(" AND ");
restrictions.keySet().stream().filter((column) -> (restrictions.get(column) != null)).map((column) -> {
StringBuilder builder = new StringBuilder();
builder.append(column).append("='").append(restrictions.get(column)).append("'");
return builder;
}).map((builder) -> builder.toString()).forEach((term) -> {
joiner.add(term);
});
System.out.println(joiner.toString());
}
}
Output:
id='foo' AND name='bar'
Just try to search for questions on "how to iterate over a map in java". How to efficiently iterate over each Entry in a Map? should give you an example.
As for comment, below can be the code, though you can easily optimize it:
StringBuffer clause = new StringBuffer();
for(Map.Entry<String, String> entry : restrictions.entrySet()) {
clause.append(entry.getKey()).append(\"=\").append(entry.getValue());
clause.append(" AND ");
}
String strClause = clause.toString();
strClause = strCluase.subString(0, strClause.length() - 5); //5 is length of " AND "
This question has been answered before. I would prefer using Colin Hebert answer in my opinion.
Your if-else would be fine but you could always override the functions to meet your needs thanks to OOP (code re-usability).
What you want to achieve could be done in various ways and everyone has his own way of coding.
I am trying to add an object inside an object using recursion. My object contains an arrayList and I am trying to add my objects to this arrayList. But instead of adding a new object, my objects are being replaced.
My code which is doing this: This is where the logic of adding an object is being done. But it is being replaced instead.
private ArrayList<SubChapters> recursiveSubChapters(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> linkedHashMap, Boolean isSubTree){
SubChapters subChapters = new Subchapters();
ArrayList<SubChapters> alchildUnits = new ArrayList<SubChapters>();
final String chapterId = linkedHashMap.get(tree.getUnitID()).get("unit_num");
final String chapterName= linkedHashMap.get(tree.getUnitID()).get("unit_name");
if (!isSubTree) {
subChapters.set(chapterId);
subChapters.setTreeName(chapterName);
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
subChapters.hasSubUnits(true);
for (ReportingTree subTree: branches) {
subChapters.setSubChapters(recursiveSubChapters(subTree, linkedHashMap, false));
//This is where the logic of adding an object is being done. But it is being replaced instead.
}
alchildUnits.add(subChapters);
}
return alchildUnits;
}
My guess is that I am messing somewhere in the loop here but I am not able to figure out where I am messing up. Thanks in advance for any suggestions or help.
My subChapters class:
public String subChapterID;
public String subChapterName;
public boolean isSubTree= false;
public ArrayList<SubChapters> subChapters;
and getters and setters.
I have coded the same solution to return a string and see the order on a jsp. It works just fine. I am not able to apply the same to my issue here.
private String recursive(ReportingTree tree, LinkedHashMap<String, HashMap<String, String>> listUnitInfo, boolean isTop) {
final String unitID = tree.getUnitID();
final HashMap<String, String> unit = listUnitInfo.get(unitID);
String output = "";
if (!isTop) {
output += "<li>" + unit.get("unit_num") + "/" + unit.get("unit_name") + "";
}
final ArrayList<ReportingTree> branches = tree.getBranches();
if (branches != null) {
if (isTop) {
output += "<li>" + unit.get("unit_num") + "/" + unit.get("unit_name") + "";
}
output += "<ul>\n";
for (ReportingTree subTree : branches) {
output += recursive(subTree, listUnitInfo, false);
}
output += "</ul>";
} else {
if (isTop) {
output += "<li>No units match your criteria.";
}
}
output += "</li>\n";
return output;
}
What you're doing is subChapters.setSubChapters, what I think you're trying to do is
subChapters.addSubChapters.
The reason why it works with the strings is because you're using += to add
the new string to the old string. Doing setSubChapters would be the same as using = with the strings.
addSubChapters would be a method that should add something to an ArrayList variable inside your subChapters class.
I have a string in the format nm=Alan&hei=72&hair=brown
I would like to split this information up, add a conversion to the first value and print the results in the format
nm Name Alan
hei Height 72
hair Hair Color brown
I've looked at various methods using the split function and hashmaps but have had no luck piecing it all together.
Any advice would be very useful to me.
Map<String, String> aliases = new HashMap<String, String>();
aliases.put("nm", "Name");
aliases.put("hei", "Height");
aliases.put("hair", "Hair Color");
String[] params = str.split("&"); // gives you string array: nm=Alan, hei=72, hair=brown
for (String p : params) {
String[] nv = p.split("=");
String name = nv[0];
String value = nv[1];
System.out.println(nv[0] + " " + aliases.get(nv[0]) + " " + nv[1]);
}
I really do not understand what you problem was...
Try something like this:
static final String DELIMETER = "&"
Map<String,String> map = ...
map.put("nm","Name");
map.put("hei","Height");
map.put("hair","Hair color");
StringBuilder builder = new StringBuilder();
String input = "nm=Alan&hei=72&hair=brown"
String[] splitted = input.split(DELIMETER);
for(Stirng str : splitted){
int index = str.indexOf("=");
String key = str.substring(0,index);
builder.append(key);
builder.append(map.get(key));
builder.append(str.substring(index));
builder.append("\n");
}
A HashMap consists of many key, value pairs. So when you use split, devise an appropriate regex (&). Once you have your string array, you can use one of the elements as the key (think about which element will make the best key). However, you may now be wondering- "how do I place the rest of elements as the values?". Perhaps you can create a new class which stores the rest of the elements and use objects of this class as values for the hashmap.
Then printing becomes easy- merely search for the value of the corresponding key. This value will be an object; use the appropriate method on this object to retrieve the elements and you should be able to print everything.
Also, remember to handle exceptions in your code. e.g. check for nulls, etc.
Another thing: your qn mentions the word "sort". I don't fully get what that means in this context...
Map<String, String> propsMap = new HashMap<String, String>();
Map<String, String> propAlias = new HashMap<String, String>();
propAlias.put("nm", "Name");
propAlias.put("hei", "Height");
propAlias.put("hair", "Hair Color");
String[] props = input.split("&");
if (props != null && props.length > 0) {
for (String prop : props) {
String[] propVal = prop.split("=");
if (propVal != null && propVal.length == 2) {
propsMap.put(propVal[0], propVal[1]);
}
}
}
for (Map.Entry tuple : propsMap.getEntrySet()) {
if (propAlias.containsKey(tuple.getKey())) {
System.out.println(tuple.getKey() + " " + propAlias.get(tuple.getKey()) + " " + tuple.getValue());
}
}