Iterate and update values in a map - dart

I have a map called oldMap with generics Map<String, List<int>>. I need to replace all the values in the oldMap. I have newValues with is off type List<List<int>> for each value. The keys will be the same. But need a way to iterate through newValues and add to the keys making a new map.
eg
oldMap = {'2': [14],'4': [11],'6': [2]}
newValues = [[11], [12], [19] ]// These values need to be in new map
newMap = {'2': [11],'4': [12],'6': [19]}

If you just want to replace the values in the existing key order, you can do:
var newMap = Map.fromIterables(oldMap.keys, newValues);
If you need some other key order, you need to figure out which, and then do something like:
var newMap = Map.fromIterables(sortKeysSomehow(oldMap.keys), newValues);
If you want to update the values in place, you can do:
var i = 0;
for (var key in map.keys) map[key] = newValues[i++];
or
var i = 0;
map.updateAll((k,v) => newValues[i++]);

Related

How do I convert an array in a map to array of strings

I'm trying to convert this map {[string1,string2]}
in to an array like this
[string1, string2]
in dart
A declaration of that kind in Dart is a Set(which is like a list but cannot have duplicates) of Lists, given that to get the first value you should just use
obj.first
(Sets are declared like maps but without any key)
This is a Set.
So you can do this for convert it to list:
Set<List<String>> map = {['string1','string2']};
List list = [];
map.forEach((k) {
k.forEach((item) => list.add(item));
});
as already mentioned in other answers this is a Set
you can easy convert it to List like this
var mySet = {['string1', 'string2']};
var list = mySet.expand((e) => e).toList();
print(list); // [string1, string2]
The 'map' you gave has one key (list of strings), which seems to be missing a value.
If your map looked something like this:
Map<List<String>, int> map = {[string1,string2]: 0};
Then you could get an Iterable of your keys (or values if you wish) with:
dynamic temp = map.keys //for the keys or
//or temp = map.values //for the values
You can further convert that Iterable into a List by calling the function toList() on it:
List<String> myList = temp.toList();
I hope this answered your question.
And if you are not sure what the type of your object is, use:
print(yourObject.runTimeType);

how to select random element from Map in dart?

How to select random key (element) from Map?
I can do it using map.keys.toList(), as in the code below, but I wonder if there is more direct way?
import "dart:math";
void main() {
var map = {'a' :1, 'b':2, 'c':3};
final _random = new Random();
var keys = map.keys.toList();
var element = keys[_random.nextInt(keys.length)];
var r = map[element];
print(r);
}
There is no simple way to pick a "random" key from a map.
I assume that "random" here means to pick it uniformly at random among the keys of the map.
For that, you need to pick a random number in the range 0..map.length - 1. Then you need to get the corresponding key. Since Map.key is an iterable, you can't assume that you can do constant-time lookup in it, but you can use elementAt to get a specific iterable item without creating a new list.
So, basically:
randomKey(Map map) =>
map.keys.elementAt(new Random().nextInt(map.length));
(like you do it, but without the toList).
If you need more than one key, you are probably better off converting the keys to a list once, and then do lookups in the list in constant time. Example:
Iterable randomKeys(Map map) sync* {
var keys = map.keys.toList();
var rnd = new Random();
while (keys.length > 0) {
var index = rnd.nextInt(keys.length);
var key = keys[index];
keys[index] = keys.last;
keys.length--;
yield key;
}
}
On top of getting better performance, taking a copy of the keys also avoids concurrent modification errors.
If you are selecting multiple random values from the list and you want to make sure you never select an entry more than once, you can take the keys or values as a list, shuffle it then iterate through it.
This is not very efficient if only a small fraction of the entries in the map are to be selected.
void main() {
var map = { 'a' :1, 'b':2, 'c':3 };
// Keys
var keys = map.keys.toList()..shuffle();
for(var k in keys) {
print('$k, ${map[k]}');
}
// Values
var values = map.values.toList()..shuffle();
for(var v in values) {
print(v);
}
}
https://dartpad.dartlang.org/e49012d93f7451af1662ad113f0aab95
I guess this is not what you're looking for, but actually it's a line shorter ;-)
void main() {
var map = {'a' :1, 'b':2, 'c':3};
final _random = new Random();
var values = map.values.toList();
var element = values[_random.nextInt(values.length)];
print(element);
}
DartPad example
You can use the dart_random_choice package to help you. While Map itself is not an iterable, you can use the Map.keys method to get an iterable and do the following:
import 'package:dart_random_choice/dart_random_choice.dart';
void main() {
var map = { 'a': 1, 'b': 2, 'c':3 };
var r = map[randomChoice(map.keys)];
print(r);
}

Receiving array in route data to be used in Where func + MVC

I am receiving an array in route data containing different string values. Since I don't know how many string values I am going to receive, I cant have a definite Where function. Hence I am looping through the array and making multiple calls to DB set, fetching the result and adding it into another Master List. Please see code below.
public JsonResult GetModels(string brand)
{
string[] brands = brand.Split(seperator);
MasterList.Clear();
for (int i = 0; i < brands.Length; i++)
{
tempString = brands[i];
tempList = db.Devices.Where(r => r.Brand.Equals(tempString)).Select(r => new MySelectList { Value = r.PhoneModel, Text = r.PhoneModel }).Distinct().ToList();
for (int a = 0; a < tempList.Count; a++)
MasterList.Add(tempList[a]);
}
return Json(MasterList, JsonRequestBehavior.AllowGet);
}
Is there a way I can somehow avoid looping through the array and use it directly in Where function? Meaning Where function can look into values of the array and return result based on it.
You can do this by using Contains. This effectively generates an SQL IN clause:
tempList = db.Devices.Where(r => brands.Contains(r.Brand));

Neo4j BatchInserter using setNodeProperties to set an array with values

I am using the BatchInserter instance to get and set properties for nodes.
My data have multiple values in some properties.
property value
======== =========
synonym animal
synonym mammalian
I want to put this values, in the same property in the same node.
I have used the following code snippet to read and set values:
String[] values = {"animal", "mammalian"};
for (int i = 0; i < values.length(); i++) {
Map<String, Object> nodeProps = db.getNodeProperties(0); // Node 0 properties
nodeProps.put("synonym", values[i]);
db.setNodeProperties(0, nodeProps);
}
In the first iteration property synonym gets value animal. In the second iteration, the property is overridden by the value mammalian.
My question is: How can I get the previous value(s), add the new one and set the property to the node so I can get synonym=['animal', 'mammalian'] in graph?
If you want to have multiple values on a node/relationship property you need to use arrays. So you have on property synonyms with a String[] as value:
To amend an existing property:
String[] values = {"animal", "mammalian"};
Map<String, Object> nodeProps = db.getNodeProperties(0);
String[] existingValues = nodeProps.get("synonym");
// using org.apache.commons.lang.ArrayUtils from Apache Commons Lang:
String[] amendedValues = ArrayUtils.addAll(existingValues, values);
nodeProps.put("synonym", amendedValues);
db.setNodeProperties(0, nodeProps);

Difference between an object and a dictionary?

What exactly is the difference between an object and a dictionary in Actionscript?
var obj:Object = new Object();
obj.something = "something";
var dict:Dictionary = new Dictionary();
dict.something = "something";
trace(obj.something, dict.something);
The trace statement seems identical...
I think the example here highlights at least one of the most significant differences, which is strict equality in comparing keys.
In summary, dictionary[key] does NOT necessarily return the same value as dictionary["key"], even if key.toString() equals "key".
However, object[key] will return the same value as object["key"], if key.toString() equals "key".
Object() uses strings as keys, while Dictionary() uses objects as keys.
See http://gskinner.com/blog/archives/2006/07/as3_dictionary_.html

Resources