How to iterate through single <key, value> pairs of List in dart - list

I have 2 Lists (uid and url) that are growable, and I need to set the first List as the key and the second as value. At some point, i'll have a 3rd List (randomUids) which will be keys and will print out the corresponding values. Here is the example code:
List<String> uid = ["uid1", "uid2","uid3","uid4"]; //Lists will grow larger after a while
List<String> url = ["url1","url2","url3","url4"];
List<String> randomUids = ["uid4", "uid2"];
When I try:
Map<List, List> mapKeyValue = Map();
mapKeyValue[uid] = url;
print( uid.contains(randomUids));
I get a false. Also, the print returns uid and url Lists as 2 long indices instead of separate Strings. How can I iterate the List so that url.contains(randomUids) is true. Also how can I print out the values of randomUids.

When I try:
print( uid.contains(randomUids));
I get a false.
Your code asks if uid (a List of Strings) contains randomUids (another List of Strings). It returns false because uid's elements are not Lists; they're Strings.
Presuming that you want the nth element of uid to correspond to the nth element of url, and you can guarantee that uid.length == url.length, you can construct a Map of UIDs to URLs:
assert(uid.length == url.length);
var uidMap = <String, String>{
for (var i = 0; i < uid.length; i += 1)
uid[i]: url[i],
};
And then you can iterate over randomUids and do lookups:
for (var uid in randomUids) {
if (uidMap.containsKey(uid)) {
print(uidMap[uid]);
}
}

Related

Sort list flutter

I'm looking for a simplest way to sort list based on given value instead of using two list.
Example I have list [a,b,c,d], with a given value d,I can sort it like this:
But if I have an object list, how can I sort it based on given value?
Example
List<ABC> list = [{fid:1,name:"a"},{fid:2,name:"b"},{fid:3,name:"c"},{fid:4,name:"d"}]
I have value 3. I want to sort the list become
List<ABC> list = [{fid:3,name:"c"},{fid:1,name:"A"},{fid:2,name:"b"},{fid:4,name:"d"},{fid:4,name:"d"}]
You just need to perform custom sorting here, rest of the things will remain same.
List list = [{"fid":1,"name":"z"},{"fid":10,"name":"b"},{"fid":5,"name":"c"},{"fid":4,"name":"d"}];
list.sort((a,b)=> a["fid"].compareTo(b["fid"]));
int fidIndex=4;
int indexToRemove=list.indexWhere((element) => element["fid"]==fidIndex);
Map<String,dynamic> removedItem= list.removeAt(indexToRemove);
list.insert(0,removedItem);
print(list);
You can sort list using comparator:
const list = [{fid:1,name:"a"},{fid:2,name:"b"},{fid:3,name:"c"},{fid:4,name:"d"}]
const fixedFid = 3
const sortedList = list.sort( (item1, item2) => {
if (item1.fid === fixedFid){
return -1
}
if (item2.fid == fixedFid){
return 1
}
return item1.fid.localeCompare(item2.fid)
})

Kotlin aggregation function

I need to write somehow a function, that aggregates results in a list.
I'm working with an Order dto (java class)
public class Order {
private Long orderId;
private String description;
...
}
I have two APIs, the one that return orders and the other one that returns suborders. So i retrieve all orders and get all suborders in a loop by predefined ids:
// for example i have a predefined list of order id's
List<Long> orderIds = listOf(1L, 2L, 3L, 4L, 5L)
val allOrders = orderIds.map {
// at first i retrieve an order
val order = orderService.getOrderById(it.orderId)
// then i get a list of suborders
val suborders = suborderService.getSubordersByOrderId(it.orderId)
// ?
}
How can i combine order (Order) and suborders (List) to a list of Order and then all the elements of nested list into a single list?
I think flatMap is what you want:
val allOrders: List<Order> = orderIds.flatMap {
val order = orderService.getOrderById(it)
val suborders = suborderService.getSubordersByOrderId(it)
suborders + order
}
It flatten all the items of the returned list into one single list altogether.

How to get element in specific index from NSMutable dictionary (Swift 3)

I need to get the first element from NSMutable dictionary. I tried to get the element using for loop. but I am not getting the correct element because the Dictionary does not follow order. Is there any way I can get the element?
Here is my code:
for (count, i) in myMutableDict.enumerated() {
if count == 2 {
print(i.key)
}
}
As you know dictionary is un ordered collection Type.
let dictionary:Dictionary = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
for(index,obj) in dictionary.enumerated() {
print("index- \(index) - Object- \(obj)");
print("key- \(obj.key) - value- \(obj.value)");
}
Enumeration will provide you index and Objects of dictionary as above code says. If you want to work with index then you need to get all keys and keep it sorted so that you can get your key by providing index. And from that key you can get value from dictionary object. Piece of code is given below.
var keyList = Array(dictionary.keys);
keyList = keyList.sorted();
print("keyList \(keyList)");
let keyAtIndex = keyList[1];
print("value = \(dictionary[keyAtIndex]!)");

issues when Iterate Map with list as value using groovy

def map = new HashMap<String,List<String>>()
def list = new ArrayList<String>()
def list1 = new ArrayList<String>()
list.add("hello1")
list​.add("world1")
list.add("sample1")
list.add("sample1")​​​​​​​​​​​​​​​​​​​​​​​​
list1.add("hello2")
list1.add("world2")
list1.add("sample2")
list1.add("sample2")
map.put("abc",list)
map.put("bcd",list1)
def data = new ArrayList<String>()
for(e in map){
println "key = ${e.key} value=${e.value}"
// data = "${e.value} as String[]"
data = "${e.value}"
println "size ${data.size()} " --(B)
check(data)
​}
def check(input)
{
println "${input.size()}" ---(A)
for(item in input){
print "$item "​​​​​​​​​​​​​​​​​}
​}​
I have to pass string[] to another java function from this groovy script. so I am trying to read the array list and then convert it into String array. But the problem is when I assign {e.value} to variable data and try to get the size data.size() (both step (A) and (B) ). and the size is 34. It is counting each character not the word as whole from the list. I want to iterate over each word from the list. Kindly let me know how to resolve this problem.
sample output is
key = abc value=[hello1, world1, sample1, sample1]
size 34
Here is the groovified vesion of creating the map and accessing it:
def map = [abc:['hello1', 'world1','sample1', 'sample1'], bcd:['hello2', 'world2','sample2', 'sample2']]
map.collect{ println "key: ${it.key}, list: ${it.value}, and size: ${it.value.size()}" }
Output:
key: abc, list: [hello1, world1, sample1, sample1], and size: 4
key: bcd, list: [hello2, world2, sample2, sample2], and size: 4
If you want to convert a list to an array you can just do it:
def list = ['hello1', 'world1','sample1', 'sample1']
assert list instanceof List
def array = list as String[]
assert array instanceof String[]
assert !(array instanceof List)

For loop to access dictionary

I have a NSDictionary of type String:AnyObject, and I want to have it be type String:String. How can I convert them with the same key to type string using a loop? I would think I could figure it out, but Xcode 6 sourcekit keeps crashing whenever I put in a for loop for the dictionary.
PS. I'm writing this in Swift, not Obj-C.
This way you can loop over the dictionary for objects:AnyObject:
let dict = ["A":1, "B":2, "C":3]
var string = ""
for object in dict.values {
string += "\(object)"
}
// string = "312"
If you want to loop over just the keys change to .keys as in the following:
for key in dict.keys {
string += key
}
// string = "CAB"
Finally to loop over both keys and values with a Tuple (key, object) :
let dict = ["A":1, "B":2, "C":3]
var string = ""
var sum = 0
for (key, object) in dict {
string += key
sum += object
}
// sum = 6
// string = "CAB"
Note: This works with Beta 3.