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)
})
Related
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]);
}
}
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.
I'm trying to sort an entire list according to one property. Afterwards I'd like to sort this list according to a second property, but in groups of 4. So, after sorting the list once, I want to look at the first 4 positions and sort only these 4 according to the second property - then move on to the next 4 positions and sort these again, and so on...
This is what I have so far:
class myElements {
int Position;
String text;
int Top;
int Left;
myElements(int Position, String text, int Top, int Left){
this.Position = Position;
this.text = text;
this.Top = Top;
this.Left = Left;
}
}
var FirstList = new List<myElements>();
var newList = new List<myElements>();
Adding Elements to my first list:
myElements Test = myElements(ElementNumber, text, Top, Left);
FirstList.add(Test);
Then sorting for the first time according to 'Top':
Comparator<myElements> TextComparator = (a, b) => a.Top.compareTo(b.Top);
FirstList.sort(TextComparator);
Here is where I'm stuck. I'm trying to sort the list again, but only in groups of 4 - this time according to 'Left':
for (int i = 0; i < FirstList.length; i += 4) {
Comparator<myElements> TextComparator2 = (a, b) =>
a.Left.compareTo(b.Left);
newList.addAll(FirstList.sublist(i, i + 3).sort(TextComparator2)); //this line does not work
}
I think I am stuck trying to access my sorted sublist: (FirstList.sublist(i, i + 4).sort(TextComparator2) . If I could add these to a new list, it should work.
However any other suggestions are more than welcome.
Thanks so much!
newList.addAll(FirstList.sublist(i, i + 3).sort(TextComparator2)); //this line does not work
Your code is almost correct. You have the right idea, but you ended up trying to do too much in one line of code.
Breaking it down a bit, your code is equivalent to:
var sublist = FirstList.sublist(i, i + 3);
newList.addAll(sublist.sort(...)); // Does not work
And that doesn't work because List.sort does not return a value. It mutates the list instead of returning a new list.
It would work if you instead did:
var sublist = FirstList.sublist(i, i + 3);
sublist.sort();
newList.addAll(sublist);
Also, List.sublist uses an exclusive end index. If you want to create sublists with 4 elements, you would need to use sublist(i, i + 4).
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]!)");
I have added hashmap to a list
Here is my list which consists of three different hashmaps.
{504=1111.07, 502=969.64, 501=823.43, 503=680.2, 512=669.03, 505=647.0}
{504=235.18, 502=205.24, 501=174.29, 503=143.98, 512=141.61, 505=136.95}
{504=235.18, 502=205.24, 501=174.29, 503=143.98, 512=141.61, 505=136.95}
I want to add all values with key as 504
Ex: 1111.07+235.18+235.18
How can i do this?
def list = [
[504:1111.07, 502:969.64, 501:823.43, 503:680.2, 512:669.03, 505:647.0],
[504:235.18, 502:205.24, 501:174.29, 503:143.98, 512:141.61, 505:136.95],
[504:235.18, 502:205.24, 501:174.29, 503:143.98, 512:141.61, 505:136.95]
]
assert list.sum { it[504] } == 1581.43
should do.