Libraries to convert HashMap to printable form - hashmap

I know you can use an iterator to print the map, but are there perhaps any libraries or methods that offer a way to print a HashMap in a nice, readable way?

Here, I wrote a quick method for you. Makes maps very easy to read.
public static <K,V> void printMap(Map<K,V> map){
for(K key : map.keySet())
System.out.println("Key: " + k + " || Value: " + map.get(k));
}
This will work for any type of key <K> and type of value <V>.

Related

how do you represent this.println in a sequence diagram?

public class ReportPrinter {
public static void printStudentReport(Student s) {
CorsoDiLaurea cdl = s.getCorsoDiLaurea();
Carriera c = s.getCarriera();
String a = s.getInfoAnagrafiche();
this.println (a + "\n" + cdl.detailString() + "\nCarriera:");
for(EsameSostenuto e: c.getEsamiSostenuti() ) {
this.println(e.nome + "-" + e.cfu + "-" + e.getVoto() );
}
this.println ("Media: " + c.get.Media() );
}
/*any code omitted */
}
I have more or less arrived at this solution (below) but how is this managed? the println method is part of System.Out so you need to create a lifeline?
Well, yes. And no. It always depends on your audience. SDs are not meant for graphical programming but to show (more or less) collaboration between objects. Preferably only complicated ones. So you are asking for a triviality. And probably nobody is interested how the println will be worked at in the system stomach. Except you want to implement the println itself. So there are three ways. Either you create a lifeline for the according system object and pass that as a message. Or you simply (!) add a note that the result will be printed. Finally you can just skip it. The println itsef would be (I guess) of lessest interest and you are more about where the data for it will be derived from.
In short: don't overdo SDs. KISS
N.B. The create messages in your diagram go slightly upward. That's not so good (I haven't checked whether that's actually wrong). But time goes down in a SD. So that would be a time travel back. Either the messages are straight or they are down (if you want to show some timeing constraint).

How to avoid inserting duplicate values in a HashMap?

Let say we have :
Map hm = new HashMap();
How to avoid putting duplicate values(Emplyees) in this HashMap?
I assume you are coding in Java, so:
if(!myMap.containsKey(myKey)){
myMap.put(myKey, myValue);
}
The good thing with HashMap is that the containsKey method takes constant time (or constant amortized time) regardless of the number of elements in your map so you can call it without bothering of the time it may take!
If you use an other language, the logic remains the same.
I think duplicate values in Map can be removed using this generic method if your userdefined object is overridden with equals and hashcode from object class
public static <K, V > Map<K,V> genericMethodtoDeleteMapduplicate(Map<K, V> pMap) {
Map<K,V> mapWithoutDup=new HashMap<>();
Set<V> totalvaluesPresent=new HashSet<>();
for (Map.Entry<K, V> a : pMap.entrySet()) {
if(totalvaluesPresent.add(a.getValue())){
mapWithoutDup.put(a.getKey(), a.getValue());
}
}
return mapWithoutDup;
}
Not sure what language you are using but in java for Hashmap their are:
boolean containsKey(Object key)
- Returns true if this map contains a mapping for the
specified key.
and
boolean containsValue(Object value)
- Returns true if this map maps one or more keys to the
specified value.
Just call which ever one makes more sense for you to check if the entry is already in the map, if it is then you know its a duplicate, otherwise put it in. I'm certain whatever language you are using will have something similar!!

What is the use of "use" keyword/method in groovy?

I read use keyword in Groovy. But could not come out with, for what it has been exactly been used. And i also come with category classes, under this topic,what is that too? And from, Groovy In Action
class StringCalculationCategory {
static def plus(String self, String operand) {
try {
return self.toInteger() + operand.toInteger()
} catch (NumberFormatException fallback) {
return (self << operand).toString()
}
}
}
use (StringCalculationCategory) {
assert 1 == '1' + '0'
assert 2 == '1' + '1'
assert 'x1' == 'x' + '1'
}
With the above code, can anyone say what is the use of use keyword in groovy? And also what the above code does?
See the Pimp My Library Pattern for what use does.
In your case it overloads the String.add(something) operator. If both Strings can be used as integers (toInteger() doesn't throw an exception), it returns the sum of those two numbers, otherwise it returns the concatenation of the Strings.
use is useful if you have a class you don't have the source code for (eg in a library) and you want to add new methods to that class.
By the way, this post in Dustin Marx's blog Inspired by Actual Events states:
The use "keyword" is actually NOT a keyword, but is a method on
Groovy's GDK extension of the Object class and is provided via
Object.use(Category, Closure). There are numerous other methods
provided on the Groovy GDK Object that provide convenient access to
functionality and might appear like language keywords or functions
because they don't need an object's name to proceed them. I tend not
to use variables in my Groovy scripts with these names (such as is,
println, and sleep) to avoid potential readability issues.
There are other similar "keywords" that are actually methods of the Object class, such as with. The Groovy JDK documentation has a list of such methods.
A very good illustration is groovy.time.TimeCategory. When used together with use() it allows for a very clean and readable date/time declarations.
Example:
use (TimeCategory) {
final now = new Date()
final threeMonthsAgo = now - 3.months
final nextWeek = now + 1.week
}

Why does Processing think I'm passing an int into the color() function at the end of this code?

Preface: I'm working with Processing and I've never used Java.
I have this Processing function, designed to find and return the most common color among the pixels of the current image that I'm working on. the last line complains that "The method color(int) in the type PApplet is not applicable for the arguments (String)." What's up?
color getModeColor() {
HashMap colors = new HashMap();
loadPixels();
for (int i=0; i < pixels.length; i++) {
if (colors.containsKey(hex(pixels[i]))) {
colors.put(hex(pixels[i]), (Integer)colors.get(hex(pixels[i])) + 1);
} else {
colors.put(hex(pixels[i]),1);
}
}
String highColor;
int highColorCount = 0;
Iterator i = colors.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if ((Integer)me.getValue() > highColorCount) {
highColorCount = (Integer)me.getValue();
highColor = (String)me.getKey();
}
}
return color((highColor);
}
The Processing docs that I'm looking at are pretty sparse on the HashMap so I'm not really sure what's going on inside it, but I've been augmenting what's available there with Java docs they point to. But I'm not really grokking what's happening with the types. It looks like the key in the HashMap needs to be a string and the value needs to be an integer, but they come out as objects that I have to cast before using. So I'm not sure whether that's causing this glitch.
Or maybe there's just a problem with color() but the docs say that it'll take a hex value which is what I was trying to use as the key in the HashMap (where I'd rather just use the color itself).
Now that I've talked through this, I'm thinking that the color() function sees the hex value as an int but the hex() function converts a color to a string. And I don't seem to be able to convert that string to an int. I guess I could parse the substrings and reconstruct the color, but there must be some more elegant way to do this that I'm missing. Should I just create a key-value-pair class that'll hold a color and a count and use an arraylist of those?
Thanks in advance for any help or suggestions you can provide!
I'll dig deeper into this, but an initial thought is to employ Java generics so that the compiler will complain about type issues (and you won't get runtime errors):
HashMap<String,Integer> colors = new HashMap<String,Integer>();
So the compiler will know that keys are Strings and elements are Integers. Thus, no casting will be necessary.
I didn't figure it out, but I did work around it. I'm just making my own string from the color components like:
colors.put(red(pixels[i]) + "," + green(pixels[i]) + "," + blue(pixels[i]),1)
and then letting the function drop a color out like this:
String[] colorConstituents = split(highColor, ",");
return color(int(colorConstituents[0]), int(colorConstituents[1]), int(colorConstituents[2]));
This doesn't really seem like the best way to handle it -- if I'm messing with this long-term I guess I'll change it to use an arraylist of objects that hold the color and count, but this works for now.

Best way to build object from delimited string (hopefully not looped case)

this question feels like it would have been asked already, but I've not found anything so here goes...
I have constructor which is handed a string which is delimited. From that string I need to populate an object's instance variables. I can easily split the string by the delimited to give me an array of strings. I know I can simply iterate through the array and set my instance variables using ifs or a switch/case statement based on the current array index - however that just feels a bit nasty. Pseudo code:
String[] tokens = <from generic string tokenizer>;
for (int i = 0;i < tokens.length;i++) {
switch(i) {
case(0): instanceVariableA = tokens[i];
case(1): instanceVarliableB = tokens[i];
...
}
}
Does anyone have any ideas of how I do this better/nicer?
For what it's worth, I'm working in Java, but I guess this is language independant.
Uhm... "nasty" is in the way the constructor handles the parameters. If you can't change that then your code snippet is as good as it may be.
You could get rid of the for loop, though...
instanceVariableA = tokens[0];
instanceVariableB = tokens[1];
and then introduce constants (for readibilty):
instanceVariableA = tokens[VARIABLE_A_INDEX];
instanceVariableB = tokens[VARIABLE_B_INDEX];
NOTE: if you could change the string parameter syntax you could introduce a simple parser and, with a little bit of reflection, handle this thing in a slightly more elegant way:
String inputString = "instanceVariableA=some_stuff|instanceVariableB=some other stuff";
String[] tokens = inputString.split("|");
for (String token : tokens)
{
String[] elements = token.split("=");
String propertyName = tokens[0];
String propertyValue = tokens[1];
invokeSetter(this, propertyName, propertyValue); // TODO write method
}
Could you not use a "for-each" loop to eliminate much of the clutter?
I really think the way you are doing it is fine, and Manrico makes a good suggestion about using constants as well.
Another method would be to create a HashMap with integer keys and string values where the key is the index and the value is the name of the property. You could then use a simple loop and some reflection to set the properties. The reflection part might make this a bit slow, but in another language (say, PHP for example) this would be much cleaner.
just an untested idea,
keep the original token...
String[] tokens = <from generic string tokenizer>;
then create
int instanceVariableA = 0;
int instanceVariableB = 1;
if you need to use it, then just
tokens[instanceVariableA];
hence no more loops, no more VARIABLE_A_INDEX...
maybe JSON might help?
Python-specific solution:
Let's say params = ["instanceVariableA", "instanceVariableB"]. Then:
self.__dict__.update(dict(zip(params, tokens)))
should work; that's roughly equivalent to
for k,v in zip(params, tokens):
setAttr(self, k, v)
depending on the presence/absence of accessors.
In a non-dynamic language, you could accomplish the same effect building a mapping from strings to references/accessors of some kind.
(Also beware that zip stops when either list runs out.)

Resources