I have a map where the values are sets of integers. What i'd want to do is to get in the best way possible (using only the Java API would be great) the union of all the sets of Integers.
Map<Long, Set<Integer>> map;
What I thought so far is to loop through the values() of the map and manually add to the big Set:
Set<Integer> bigSet = new HashSet<>();
Iterator<Set<Integer>> iter = map.values().iterator();
while(iter.hasNext())
bigSet.addAll(iter.next());
Also a collection for the union backed by the map would be great.
Unfortunately i am stuck with Java 7.
On the one hand you could use the new Java 8 fluent interface
import static java.util.stream.Collectors.toSet;
Set<Integer> myUnion = map
.values()
.stream()
.flatMap(set -> set.stream())
.collect(toSet());
On the other hand I would suggest taking a look at Guava's SetMultimap if you can use external libraries.
Related
I learned java and python in high school and I became very comfortable with python. I have recently started to learn kotlin, mainly for fun (the keyword for defining a function is fun so it has to be a fun language, right), but I have a little problem.
Let's suppose I have a hierarchy of classes for Chess pieces:
abstract class Piece {
...
}
class Rook : Piece() {
...
}
class Bishop : Piece() {
...
}
.
.
.
I am taking input from the user to generate the board, so if the user types r, I need to create a Rook object, if he types b, I need to create a Bishop etc.
In python, I'd probably use a dictionary that maps the input string to the corresponding class, so I can create an object of the correct type:
class Piece:
...
class Rook(Piece):
...
class Bishop(Piece):
...
.
.
.
input_map = {
'r': Rook,
'b': Bishop,
...
}
s = input_map[input()]() # use user input as key and create a piece of the correct type
I was really amazed by this pattern when I discovered it. In java, I had to use a switch case or a bunch of if else if to achieve the same result, which is not the end of the world, especially if I abstract it into a separate function, but it's not as nice as the python approach.
I want to do the same thing in kotlin, and I was wondering if there is a similar pattern for kotlin since it's a modern language like python (I know, I know, python isn't new, but I think it's very modern). I tried to look online, but it seems like I can't store a class (class, not an object) in a variable or a map like I can in python.
Am I wrong about it? Can I use a similar pattern in kotlin or do I have to fall back to the when statement (or expression)?
If I am not mistaken, a similar pattern could be achieved in java using reflection. I never got to learn reflection in java deeply, but I know it's a way to use classes dynamically, what I can do for free in python. I also heard that in java, reflection should be used as a last resort because it's inefficient and it's considered "black magic" if you understand my meaning. Does it mean that I need to use reflection to achieve that result in kotlin? And if so, is it recommended to use reflection in kotlin, and is it efficient?
I'd like to know how I can approach this problem, and I accept multiple answers and additional solutions I didn't come up with. Thanks in advance.
This can be done without reflection.
You can map the input characters to the constructors:
val pieceConstructorsByKeyChar = mapOf(
'r' to ::Rook,
'b' to ::Bishop,
// etc.
)
Getting values from a map gives you a nullable, since it's possible the key you supply isn't in the map. Maybe this is fine, if when you use this you might be passing a character the player typed that might not be supported. Then you would probably handle null by telling the player to try again:
val piece: Piece? = pieceConstructorsByKeyChar[keyPressed]?.invoke()
Or if you do the look-up after you've already checked that it's a valid key-stroke, you can use !! safely:
val piece: Piece = pieceConstructorsByKeyChar[keyPressed]!!()
Yes you can use similiar approach with Kotlin. Kotlin has many features and supports reflection. Let me write an example about your problem.
Firstly create your classes that will be generate by user input.
abstract class Piece
class Rook : Piece()
class Bishop : Piece()
Create your class map
val inputMap = mapOf(
"r" to Rook::class.java,
"b" to Bishop::class.java
)
Create an instance what you want using newInstance function. If your input map doesn't contains key you gave then it will return null.
val rook = inputMap["r"]?.newInstance()
val bishop = inputMap["b"]?.newInstance()
// null
val king = inputMap["k"]?.newInstance()
Also you can write your custom extensions to create new objects.
fun <T> Map<String, Class<out T>>.newInstance(key: String) = this[key]?.newInstance()
// Create an instance with extension function
inputMap.newInstance("r")
I am trying to convert GSON to jackson I have a method that returns a gson JsonObject. However it only creates a JsonArray, and returns that so I assume there is a simple casting there. So what would be the Jackson Equivalent? Now the method only adds one string at a time. So I need something like this:
JsonNode node = new JsonNode();
node.add("String 1");
node.add("String 2');
but would come out like this:
["String 1","String 2"]
I could create a List and map it from there, but I want to do this raw.
This seems too simple as google has given me many suggestions that are far beyond what this simple exercise requires.
And if anyone has a nice blog to tutorial on how to convert Gson to Jackson that would be great.
it is a bit tricky - you create an array node through JsonNode factory method:
ArrayNode arrNode = (ArrayNode)new JsonNode().withArray("my_array"); // arg is arrray propertry name
arrNode.add("String 1");
arrNode.add("String 2');
If you just want to create ArrayNode, ObjectMapper has method createArrayNode(), along with createObjectNode(). You can then add entries to it, as well as add node itself into other arrays, or as property in ObjectNode.
Actual construction of nodes by mapper is done using configurable JsonNodeFactory; default implementation of which simple constructs one of standard implementation types like ObjectNode and ArrayNode.
I was told by a friend that in practice/industry we should write:
Map<Class1, Class2> map = new HashMap<>();
instead of
Map<Class1, Class2> map = new HashMap<Class1, Class2>();
Is there any specific reason for this coding style?
Because the compiler will understand HashMap<> is a HashMap<Class1, Class2> and you don't need to repeat your self. Later if you want to change Class1, Class2 you will only need to change in a single place.
It's the same like some modern language like C#, Swift, Kotlin start to write var a = 5 instead of int a = 5
I've recently found the need to use a Map with a Long as the key and an ArrayList of objects as the value, like this:
Map<Long, ArrayList<Object>>
But I just read here that using a third-party library like Google Guava is recommended for this. In particular, a Multimap is recommended instead of the above.
What are the main benefits of using a library to do something so simple?
I like the ArrayList analogy given above. Just as ArrayList saves you from array-resizing boilerplate, Multimap saves you from list-creation boilerplate.
Before:
Map<String, List<Connection>> map =
new HashMap<>();
for (Connection connection : connections) {
String host = connection.getHost();
if (!map.containsKey(host)) {
map.put(host, new ArrayList<Connection>());
}
map.get(host).add(connection);
}
After:
Multimap<String, Connection> multimap =
ArrayListMultimap.create();
for (Connection connection : connections) {
multimap.put(connection.getHost(), connection);
}
And that leads into the next advantage: Since Guava has committed to using Multimap, it includes utilities built around the class. Using them, the "after" in "before and after" should really be:
Multimap<String, Connection> multimap =
Multimaps.index(connections, Connection::getHost);
Multimaps.index is one of many such utilities. Plus, the Multimap class itself provides richer methods than Map<K, List<V>>.
What is Guava details some reasoning and benefits.
For me the biggest reason would be reliability and testing. As mentioned it has been battle-tested at Google, is now very widely used elsewhere and has extensive unit testing.
When is it acceptable to do this. For example, I find myself sometimes needing to create, say, a form of tuple or something that has a key
so like a
String -> (myObj1, myObj2, myObj3)
I end up making a class to hold the myObj1 -> 3 but as you can see this class has limited fields so it seems like its a waste of a class as such.
Should I not worry about that or is it bad design to create classes for list storage purposes?
It depends on how complicated the list objects are. Most languages/frameworks have build in classes for tuples, pairs, key->value pairs, points, associative arrays and similar forms. If your objects are a little more complicated and can't find anything that fits your needs use a custom class. I don't see any problems here.
There are various options:
C# KeyValue: IList<KeyValuePair<string, string>>
C# Dictionaty: Dictionary<string, string>)
Java: Map<String, String>
Php associative arrays: $myVal = $myArray['$myKey']