If I have a list of key/value pairs, how would I convert them to a single map?
eg [{'ore': 'value'}, {'pure':'value'}, {'steel':'value}]. =>
{'ore': 'value',
'pure':'value'
'steel':'value'}
Just build a new map containing all the individual map's entries:
List<Map<Something, Other>> listOfMaps = ...;
var combinedMap = {for (var map in listOfMaps) ...map};
Use the reduce function
var v =[{'ore': 'value'}, {'pure':'value'}, {'steel':'value'}];
var w = v.reduce((a,b){
a.addAll(b);
return a;
});
Related
How can I convert 2d list to 1d list with all the elements in dart?
I have this 2d List:
List<List<int>> list2d = [[1, 2], [3, 4]];
What I want is:
List<int> list1d = [1, 2, 3, 4];
By converting the first one (2d) to the second (1d) but without writing any (for/while) loops code, if there any built-in methods like map()/where()/cast()/...etc.
Any ideas?
As other have pointed out, expand does what you want
var list2d = [[1, 2], [3, 4]];
var list1d = list2d.expand((x) => x).toList();
You can also, and perhaps preferably, use a list literal:
var list1d = [for (var list in list2d) ...list];
In general, iterable.expand((x) => e).toList() is equivalent to [for (var x in iterable) ...e].
Simply by using the reduce function like this:
List<int> list1d = list2d.reduce((value, element) {
value.addAll(element);
return value;
});
Definition:
List<T> reduce(List<T> Function(List<T>, List<T>) combine);
You can just use the .expand method:
List<int> list1d = list2d.expand((e) => e).toList();
I have a list and I want to put a condition on it. for example, I want to have items from list lst that value greater than 10:
var lst = [{"value":5 , "name":"test1"},
{"value":12 , "name":"test2"},
{"value":8 , "name":"test3"},
{"value":23 , "name":"test4"}];
/*
output: value greater than 10 =>
[{"value":12 , "name":"test2"},
{"value":23 , "name":"test4"}]
*/
You can either use the where function on iterables to filter its elements, then convert the resulting iterable back to a list, or use the list literal syntax, or a combination of the two where you "spread" the result of where:
var list = [ ... ];
var filtered1 = list.where((e) => e["value"] > 10).toList();
var filtered2 = [for (var e in list) if (e["value"] > 10) e];
var filtered3 = [... list.where((e) => e["value"] > 10)];
To filter a list base on a condition you can use List.where which takes a test function and returns a new Iterable that contains the elements that match the test.
To get a list with only the values greater than 10 you can filter you list of maps as such:
lst.where((e) => e['value'] > 10); //Returns a lazy Iterable
if you need to modify your list later you can append a .toList(), to get a new list.
try to use this code:
List lst = [{"value":5 , "name":"test1"} ,{"value":12 , "name":"test2"} , {"value":8 , "name":"test3"} , {"value":23 , "name":"test4"} ];
List newLst = lst.where( (o) => o['value'] > 5).toList();
print(newLst);
> Just try this Function, catogory_id == 1 is condition here
List<dynamic> chooseCatogory(List<dynamic> list) {
List newlist = list.where((o) => o['category_id'] == '1').toList();
return newlist;
}
I am trying to extend a list just by using add method like this
List<String> mylists = ['a', 'b', 'c'];
var d = mylists.add('d');
print(d);
It gives error
This expression has type 'void' and can't be used.
print(d);
Why i cannot save the list in a new variable? Thank you
mylists.add('d') will add the argument to the original list.
If you want to create a new list you have several possibilities:
List<String> mylists = ['a', 'b', 'c'];
// with the constructor
var l1 = List.from(mylists);
l1.add('d');
// with .toList()
var l2 = mylists.toList();
l2.add('d');
// with cascade as one liner
var l3 = List.from(mylists)..add('d');
var l4 = mylists.toList()..add('d');
// in a upcoming version of dart with spread (not yet available)
var l5 = [...myList, 'd'];
Refering Dart docs: https://api.dartlang.org/stable/2.2.0/dart-core/List-class.html
The add method of List class has return type of void.
So you were unable to assign var d.
To save list in new variable use:
List<String> mylists = ['a', 'b', 'c'];
mylists.add('d');
var d = mylists;
print(d);
First add the new String i.e. 'd'
And then assign it to new variable
How to add all the values of a map to have the total of 14000?
Map<String, int> salary = {
"user1": 4000,
"user2": 4000,
"user3": 3000,
"user4": 3000,
};
Firstly, you just care about the values of this map, not care about the keys, so we work on the values by this:
var values = salary.values;
And we can use reduce to combine all the values with sum operator:
var values = salary.values;
var result = values.reduce((sum, element) => sum + element);
print(result);
You can reference some basic of List & Map here:
https://api.dartlang.org/stable/1.10.1/dart-core/List-class.html
https://api.dartlang.org/stable/1.10.1/dart-core/Map-class.html
I Use this sample for search in Map but not work :|:
var xmenList = ['4','xmen','4xmen','test'];
var xmenObj = {
'first': '4',
'second': 'xmen',
'fifth': '4xmen',
'author': 'test'
};
print(xmenList.indexOf('4xmen')); // 2
print(xmenObj.indexOf('4xmen')); // ?
but I have error TypeError: xmenObj.indexOf$1 is not a function on last code line.
Pelease help me to search in map object simple way same as indexOf.
I found the answer:
print(xmenObj.values.toList().indexOf('4xmen')); // 2
or this:
var ind = xmenObj.values.toList().indexOf('4xmen') ;
print(xmenObj.keys.toList()[ind]); // fifth
Maps are not indexable by integers, so there is no operation corresponding to indexOf. If you see lists as specialized maps where the keys are always consecutive integers, then the corresponding operation should find the key for a given value.
Maps are not built for that, so iterating through all the keys and values is the only way to get that result.
I'd do that as:
K keyForValue<K, V>(Map<K, V> map, V value) {
for (var entry in map.entries) {
if (entry.value == value) return key;
}
return null;
}
The entries getter is introduced in Dart 2. If you don't have that, then using the map.values.toList().indexOf(value) to get the iteration position, and then map.keys.elementAt(thatIndex) to get the corresponding key.
If you really only want the numerical index, then you can skip that last step.
It's not amazingly efficient (you allocate a new list and copy all the values). Another approach is:
int indexOfValue<V>(Map<Object, V> map, V value) {
int i = 0;
for (var mapValue in map.values) {
if (mapValue == value) return i;
i++;
}
return -1;
}
You can search using .where(...) if you want to find all that match or firstWhere if you assume there can only be one or you only want the first
var found = xmenObj.keys.firstWhere(
(k) => xmenObj[k] == '4xmen', orElse: () => null);
print(xmenObj[found]);