I'm working on a small project in which I want the following to happen: I want to be able to give descriptions to words in such a way that I am able to get both pieces of information later on. Using a String array seems like it would be time consuming, and, by the way I'm interpreting what I'm reading, using the following piece of code only gives me the second written information, which is "Example Description.", because it maps the second value to the first "value" (which is a "key").
Map<String, String> exampleDictionaryThing = new HashMap<String, String>() {{
put("Example Word", "Example Description.");
}};
Just to make sure I'm understood, as English isn't really my best language, I'm trying to make a bunch of dictionary-like things where I'm able to grab both pieces of information, the two pieces of info. being a word and a description for it, but doing a bunch of String array's would A) take a lot of time and B) would be, what seems to me, an incredibly inefficient way of going about this issue.
Anybody have any ideas?
Update #1
I knew my wording would cause confusion; sorry xD. From what I've read on how I'm going about this, the line of code I've given above only allows me access to the "Example Description." line if I call the get() function. What I need is something to store two Strings and give me access to both (hopefully) without using a String array. My question is: How would I go about storing two Strings in that fashion?
If you have
HashMap<String, String> mp = new HashMap<String, String>();
which is properly populated (basically in the way you described), you can do the following in order to iterate through it (this way you have both the key and the value in your loop):
for (String word : mp.keySet()){
System.out.println("Word: [" + word + "]; Word Description: [" + mp.get(word) + "].");
}
If you want to "get both pieces of information later on" as you say, maybe you should take a look at Guava's BiMap. This data structure would allow you to recover the description given the word, or the opposite.
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html
Related
I am using Java to make an Uno game. I have a method called findCard(String cardname) whose function is to find the card in a hand of cards when the user writes in the name of the card (e.g: “Red 6”) and to return null if it can’t find the card. It works fine when I tried something like:
String card = "Red" + " " + "6";
pHand.findCard(card); // return the card Red 6
However, in the game, I will need the user to write a full command such as “deal Red 6”. Thus, I use StringTokenizer to separate the card’s name from the command:
StringTokenizer scan = new StringTokenizer(input);
String cmd = scan.nextToken(); // = "deal"
String color = scan.nextToken(); // = "Red"
String card = color + " " + scan.nextToken(); // = "Red 6"
What is wrong is when I try pHand.findCard(card); in this scenario, it only returns null no matter what was typed in.
All I know about StringTokenizer is that it can split words in a string so I don't see how these are different. Thus, it would be great if anyone can point out the reason and the solution for this.
The comments already have the solutions really... but to wrap some more advice around it:
Your Problem
You're just missing a space between the color and number.
General Advice
Make sure everything is the same case before comparing (e.g. all lower/upper).
Get rid of white space when handling tokens.
Keep variables separate; card value and card color are both unique and useful, putting them back in one string makes them less useful and harder to use and can introduce errors like yours.
Recommendation
Modify findCard() to take 2 strings, one with the card value and one with the color. Also, if you're using "red 6" as a key in a map or something, either:
Make sure you build "red 6" from "red" and "6" using a function that you use everywhere you do this. That way you can unit test the function and you're sure that you don't add a space in one spot and forget it in another spot. Generally anywhere where you duplicate code, you might mess up - so don't duplicate.
Make "card" a class and override equals and hash code to use both of these values when determining equality. Then you can use card as the key in a map fine.
Also, I kind of agree with the person who said that string spit() would be easier (just because you see it more often in code). But both should work if you're comfortable; so do it your way if you're happy :).
I'm wondering if is the way to deserialize the server response. So in my case I have an LinkedHashMap<String,Date> and returing this from server:
#Override
public LinkedHashMap<String, Date> testHMap() {
LinkedHashMap<String, Date> map = new LinkedHashMap<>();
map.put("AA", new Date());
map.put("BB", new Date());
return map;
}
I'm trying to get info about another application(gwt) so I can perform calls only via HTTP, and from upper example the HTTP response looks like : //OK['WM577vZ',4,5,2,'WM577vZ',4,3,2,2,0,1,["java.util.LinkedHashMap/3008245022","java.lang.String/2004016611","AA","java.util.Date/3385151746","BB"],0,7]
So, is there a way to get the LinkedHashMap data from this HTTP respone?
The LinkedHashMap is in that response - that response is an object stream (i.e. instead of JSON, if the same value appears twice, it will only be serialized once, which lets the content be smaller, and also allows cyclical references instead of only a flat tree).
Reading the RPC payload is done "backward" - starting from the end and reading backward, we start with 7 (the version), 0 (the flags that are set), a big [] of strings (the "string table", the strings that are needed to decode the reply, so that each string is only listed once).
Then a 1 - the first object in the stream is the type of the first entry in the string table, i.e. "java.util.LinkedHashMap/3008245022" as you are looking for. To decode a LinkedHashMap, we first need to know how it is ordered - the next 0 value tells us that it uses the default of "insertion-order", and then the next 2 says that there are two entries in the map.
Now we iterate until we've seen the two pairs of keys and values. The next value will tell us what kind of key we're looking at: 2 means to go into the string table and we see "java.lang.String/2004016611", so we know it will be a string, then the 3 shows us "AA" also from the string table. Next is 4, the type of the value for that key, predictably this "java.util.Date/3385151746" from the string table. To deserialize a date, we read a long from the payload - GWT base64-encodes these to keep them smaller - this is 'WM577vZ', the next token.
The next 4 tokens, (2, 5, 4, and 'WM577vZ') repeat this process, adding the second string key to the map, and the date value for it.
--
This particular payload isn't the kind that really shows RPC's power, but it is fairly simple to read by hand. Decoding them outside of a GWT app is currently not very easy (though I'm working on a generalized tool which should let it be decoded anywhere, but a SO answer isn't really the place to talk about it) - if you want a format that can be handled by plain JS or some other non-GWT technology, RPC likely isn't your best bet at this time.
I think you are looking for something like restyGWT.
But I don't really understand your question so I might be wrong.
Started using Hadoop recently and struggling to make sense of a few things. Here is a basic WordCount example that I'm looking at (count the number of times each word appears):
Map(String docid, String text):
for each word term in text:
Emit(term, 1);
Reduce(String term, Iterator<Int> values):
int sum = 0;
for each v in values:
sum += v;
Emit(term, sum);
Firstly, what is Emit(w,1) supposed to be doing? I notice that in all of the examples I look at the second parameter is always set to 1, but I can't seem to find an explanation on it.
Also, just to clarify - am I correct in saying that term is the key and sum in Reduce form the key-value pairs (respectively)? If this is the case, is values simply a list of 1's for each term that got emitted from Map? That's the only way I can make sense of it, but these are just assumptions.
Apologies for the noob question, I have looked at tutorials but a lot of the time I find that a lot of confusing terminology is used and overall basic things are made to be more complicated than they actually are so I'm struggling a little to make sense of this.
Appreciate any help!
Take this input as an example word count input.
Mapper will split this sentence into words.
Take,1
this,1
input,1
as,1
an,1
example,1
word,1
count,1
input,1
Then, the reducer receives "groups" of the same word (or key) and lists of the grouped values like so (and additionally sorts the keys, but that's not important for this example)
Take, (1)
this, (1)
input (1, 1)
etc...
As you can see, the key input has been "reduced" into a single element, that you can loop over and sum the values and emit like so
Take,1
this,1
input,2
etc...
Good question.
As explained, the mapper outputs a sequence of (key, value) pairs, in this case of the form (word, 1) for each word, which the reducer receives grouped as (key, <1,1,...,1>), sums up the terms in the list and returns (key, sum). Note that it is not the reducer who does the grouping; it's the map-reduce environment.
The map-reduce programming model is different from the one we're used to working in, and it's often not obvious how to implement an algorithm in this model. (Think, for example, about how would you implement a k-means clustering.)
I recommend Chapter 2 of the freely-available Mining of Massive Data Sets book by Leskovec et al. See also the corresponding slides.
I've been searching around and havn't quite found my answer.
At this moment me and along with my group have created a few classes resembling a Bank with Customer and Account and so on.
I've been struggling lately with trying to improve and secure our code by making our variable called "name" only respond to certain inputs.
In this case, I want to make it only possible for the person to enter name as such:
Atleast 2 words = (For the word part I've seen codes where you count towards the white space between but don't know yet what you do about the last word since there wont be a white space)
Max 4 words = ( Same thing here)
No special signs such as ,!%¤"#()=%/'¨. = ( for this, I've read something about "Matcher and pattern" )
Now I'm quite new to Java and I'm not asking for a code from someone, I'm asking for someone to point me in the right directions regarding codes, because alot of what i've seen like the Matcher and pattern are things that you import with downloading utils and stuff but I reckon that it's not needed and there should be a simpler more basic way as I'm not trying to get ahead of myself with copying codes just to get it done.
So yeah, the String "name" is used alot in our main class "Banklogic" where almost every method that adds something has the variable "name" in it, so it's quite important that I get this done.
I hope I was clear enough and any help would be appreciated! I'm gonna put the alarm for 3 hours before school to see what you guys have come up with so I can try and complete the code before our meeting! Thanks alot in advance :)
Since you asked for hints, you can use Regex to add such rules.
For Numbers only:
if(string.matches("[0-9\\W]")
//allow insertion of data else not
As for rules related Word Count:
string.split("\\W") will create an array separated by space character. You can count the number of elements in this array and allow/disallow input based on that.
As for no signs and only letters:
if(string.matches("[a-zA-Z\\W]")
// Allow Input else not
You can use Document Filter to implement these methods. Document filter will only allow text to be entered if you allow it to.
I hope this helped as a hint.
Also, note that \\W is for whitespaces. If you dont want to allow whitespaces, remove that char.
This is the most effective and simple way of doing the task.
EDIT:
This is a Class I wrote a little while ago to achieve such tasks. Just in case if you are interested....
This is probably a simple one and more Java related than grails but I'm a bit lost and not sure where to even start looking on this, I've googled about but am not really sure what I'm after, so would appreciate a pointer if possible please!
In the grails app I have a form which I save, all well and good. In the controller I can see the list of params it returns via a simple println and when I want to find a specific value currently I do a params.each and then compare the key to a pre defined string to find the one I want, my question is: -
Can I, and how would I, specifically say "get me the value of the parameter with the key "banana", rather than having to loop through the whole list to find it?
Also is there a way of creating a new set of secondary params, or just another plain old dictionary item (is that the right term?) where I use a regular expression to say "give me all the items whose key match the pattern "XYZ"?
It probably doesn't make much difference speed wise as the params are never that big but it'd be nice to make things more efficient where possible.
Any feedback much appreciated!
For a first question, to get 'banana' parameter you have to use:
params.banana
For second, find all with regexp:
def matched = params.findAll { it.key =~ /XYZ/ }
//or
Pattern p = ~/XYZ/
def matched = params.findAll { p.matcher(it.key).matches() }
There's a params object you can use. Eg with someurl.com?myparam=test you can access it with "params.myparam"
More information over here: http://grails.org/doc/2.2.x/ref/Controllers/params.html