Flutter/Dart how to combine values in list of maps - list

I have the following list of maps:
[
{
"id":1,
"asset_id":"name1",
"asset_price":100.00,
"asset_date":"09-09-09"
},
{
"id":2,
"asset_id":"name2",
"asset_price":50.00,
"asset_date":"10-09-09"
},
{
"id":3,
"asset_id":"name1",
"asset_price":100.00,
"asset_date":"11-09-09"
}
]
How can I produce a new list that combines duplicate asset_id and sums the price as below:
[
{
"id":1,
"asset_id":"name1",
"asset_price":200.00,
"asset_date":"09-09-09"
},
{
"id":2,
"asset_id":"name2",
"asset_price":50.00,
"asset_date":"10-09-09"
}
]
Class
int id;
String assetId;
String assetName;
String assetSymbol;
String assetImage;
double assetAmount;
String assetCurrency;
double assetPrice;
String assetDate;
Asset(
{this.id,
this.assetId,
this.assetName,
this.assetSymbol,
this.assetImage,
this.assetAmount,
this.assetCurrency,
this.assetPrice,
this.assetDate});
Map<String, dynamic> toMapWithoutId() {
final map = new Map<String, dynamic>();
map["id"] = id;
map["asset_id"] = assetId;
map["asset_name"] = assetName;
map["asset_symbol"] = assetSymbol;
map["asset_image"] = assetImage;
map["asset_amount"] = assetAmount;
map["asset_currency"] = assetCurrency;
map["asset_price"] = assetPrice;
map["asset_date"] = assetDate;
return map;
}
Map<String, dynamic> toMap() {
final map = new Map<String, dynamic>();
map["id"] = id;
map["asset_id"] = assetId;
map["asset_name"] = assetName;
map["asset_symbol"] = assetSymbol;
map["asset_image"] = assetImage;
map["asset_amount"] = assetAmount;
map["asset_currency"] = assetCurrency;
map["asset_price"] = assetPrice;
map["asset_date"] = assetDate;
return map;
}
//to be used when converting the row into object
factory Asset.fromMap(Map<String, dynamic> data) => new Asset(
id: data["id"],
assetId: data["asset_id"],
assetName: data["asset_name"],
assetSymbol: data["asset_symbol"],
assetImage: data["asset_image"],
assetAmount: data["asset_amount"],
assetCurrency: data["asset_currency"],
assetPrice: data["asset_price"],
assetDate: data["asset_date"]);
}

Related

Fetch user details from another model

I have a model(Poll) which contains another model(User) with user details.
I want to get the Username of who posted a poll
but the below is error occurred
I/flutter (21892): type 'int' is not a subtype of type 'String'
this is my model class(flutter)
import 'dart:convert';
class Poll {
Poll({
required this.id,
required this.choices,
required this.question,
required this.pubDate,
required this.createdBy,
});
late final int id;
late final List<Choices> choices;
late final String question;
late final String pubDate;
late final User createdBy;
Poll.fromJson(Map<String, dynamic> json) {
id = json['id'];
choices =
List.from(json['choices']).map((e) => Choices.fromJson(e)).toList();
question = json['question'];
pubDate = json['pub_date'];
createdBy = User.fromJson(jsonDecode(json['created_by']));
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['choices'] = choices.map((e) => e.toJson()).toList();
_data['question'] = question;
_data['pub_date'] = pubDate;
_data['created_by'] = createdBy.toJson();
return _data;
}
}
class Choices {
Choices({
required this.id,
required this.choiceText,
required this.poll,
});
late final int id;
late final String choiceText;
late final int poll;
Choices.fromJson(Map<String, dynamic> json) {
id = json['id'];
choiceText = json['choice_text'];
poll = json['poll'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['choice_text'] = choiceText;
_data['poll'] = poll;
return _data;
}
}
class User {
User({
required this.id,
required this.password,
required this.lastLogin,
required this.isSuperuser,
required this.username,
required this.firstName,
required this.lastName,
required this.email,
required this.isStaff,
required this.isActive,
required this.dateJoined,
required this.groups,
required this.userPermissions,
});
late final int id;
late final String password;
late final String lastLogin;
late final bool isSuperuser;
late final String username;
late final String firstName;
late final String lastName;
late final String email;
late final bool isStaff;
late final bool isActive;
late final String dateJoined;
late final List<dynamic> groups;
late final List<dynamic> userPermissions;
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
password = json['password'];
lastLogin = json['last_login'];
isSuperuser = json['is_superuser'];
username = json['username'];
firstName = json['first_name'];
lastName = json['last_name'];
email = json['email'];
isStaff = json['is_staff'];
isActive = json['is_active'];
dateJoined = json['date_joined'];
groups = List.castFrom<dynamic, dynamic>(json['groups']);
userPermissions = List.castFrom<dynamic, dynamic>(json['user_permissions']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['password'] = password;
_data['last_login'] = lastLogin;
_data['is_superuser'] = isSuperuser;
_data['username'] = username;
_data['first_name'] = firstName;
_data['last_name'] = lastName;
_data['email'] = email;
_data['is_staff'] = isStaff;
_data['is_active'] = isActive;
_data['date_joined'] = dateJoined;
_data['groups'] = groups;
_data['user_permissions'] = userPermissions;
return _data;
}
}
here is how I am parsing the json
List<Poll> _polls = [];
Future<bool> getOffers() async {
var url = Uri.parse(polls_uri);
try {
http.Response response = await http.get(url);
var data = json.decode(response.body);
List<Poll> temp = [];
for (var element in data) {
Poll poll = Poll.fromJson(element);
temp.add(poll);
}
_polls = temp;
return true;
} catch (e) {
print(e);
return false;
}
}
List<Poll> get polls {
return [..._polls];
}
this is where i want to display I want to display the details
ListView.builder(
itemCount: polls.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(polls[index].question),
Text(polls[index].createdBy.username),
]),
),
);
},
),
my model class(django)
class Poll(models.Model):
question = models.CharField(max_length=100)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.question
serializer
class PollSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(many=True, read_only=True, required = False)
class Meta:
model = Poll
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
views
class PollList(generics.ListCreateAPIView):
queryset = Poll.objects.all() [:20]
serializer_class = PollSerializer
Poll Json data: the key "created_by" is a model of class user... It is from the class I want to get the username
{
"id": 3,
"choices": [
{
"id": 9,
"choice_text": "Day",
"poll": 3
},
{
"id": 10,
"choice_text": "Boarding",
"poll": 3
},
{
"id": 11,
"choice_text": "Mixed",
"poll": 3
}
],
"created_by": 1,
"question": "Type of School: Day or Boarding",
"pub_date": "2022-07-21T13:29:23.445097Z"
},

Perform operation on first element and then all items of list in java stream

I want to iterate a list of object 2 times. First time I need to use only first object and perform some operation. Second time I want to perform operation on all the items of list.
In below example, I have list of TestPojo i.e. testPojoList.
Using Java stream I have tried to achieve the same in 2 steps (Operation#1 and Operation#2) Is there any better way or I can merge both of the operations in single operation? below is the piece of code:
public void Mapping() {
TestPojo testPojo1 = TestPojo.builder().name("Mike").city("Denver").company("Tesla").build();
TestPojo testPojo2 = TestPojo.builder().name("Bob").city("Atlanta").company("Tesla").build();
TestPojo testPojo3 = TestPojo.builder().name("Steve").city("Chicago").company("Tesla").build();
TestPojo testPojo4 = TestPojo.builder().name("John").city("Boston").company("Tesla").build();
List<TestPojo> testPojoList = Arrays.asList(testPojo1, testPojo2, testPojo3, testPojo4);
//Operation1
TransformedTestPojo transformedTestPojo = testPojoList.stream().findFirst().map(testPojo -> mapCompanyName(testPojo)).orElse(null);
//Operation2
List<PersonalDetails> personalDetailsList = testPojoList.stream().map(testPojo -> mapOtherDetails(testPojo)).collect(Collectors.toList());,
transformedTestPojo.setPersonalDetailsList(personalDetailsList);
System.out.println(transformedTestPojo);
}
private PersonalDetails mapOtherDetails(TestPojo testPojo) {
return PersonalDetails.builder().name(testPojo.getName()).City(testPojo.getCity()).build();
}
private TransformedTestPojo mapCompanyName(TestPojo testPojo) {
return TransformedTestPojo.builder().company(testPojo.getCompany()).build();
}
public class TestPojo {
String name;
String city;
String company;
}
public class TransformedTestPojo {
String company;
List<PersonalDetails> personalDetailsList;
}
public class PersonalDetails {
String name;
String City;
}
Following will be the output:
//Request List
{
"testPojoList": [
{
"name": "Mike",
"city": "Denver",
"company": "Tesla"
},
{
"name": "Bob",
"city": "Atlanta",
"company": "Tesla"
},
{
"name": "Steve",
"city": "Chicago",
"company": "Tesla"
},
{
"name": "John",
"city": "Boston",
"company": "Tesla"
}
]
}
//Response Object
"TransformedTestPojo":
{
"company": "Tesla",
"personalDetailsList": [
{
"name": "Mike",
"City": "Denver"
},
{
"name": "Bob",
"City": "Atlanta"
},
{
"name": "Steve",
"City": "Chicago"
},
{
"name": "John",
"City": "Boston"
}
]
}
Here are two ways to do it. But first, I created the classes. Instead of a builder I used a constructor for TestPojo. But it will still work.
class TestPojo {
String name;
String city;
String company;
public TestPojo(String name, String city, String company) {
this.name = name;
this.city = city;
this.company = company;
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
public String getCompany() {
return company;
}
#Override
public String toString() {
return String.format("[%s, %s, %s]", name, city, company);
}
}
class TransformedTestPojo {
String company;
List<PersonalDetails> personalDetailsList;
public TransformedTestPojo(String company,
List<PersonalDetails> personalDetailsList) {
this.company = company;
this.personalDetailsList = personalDetailsList;
}
public String getCompany() {
return company;
}
public List<PersonalDetails> getPersonalDetailsList() {
return personalDetailsList;
}
}
class PersonalDetails {
String name;
String City;
public PersonalDetails(String name, String city) {
this.name = name;
City = city;
}
#Override
public String toString() {
return String.format("[%s, %s]", name, City);
}
}
The Data
List<TestPojo> testPojoList =
List.of(new TestPojo("Mike", "Denver", "Tesla"),
new TestPojo("Bob", "Atlanta", "Tesla"),
new TestPojo("Steve", "Chicago", "Tesla"),
new TestPojo("John", "Boston", "Tesla"));
The Map approach using a loop
The best approach (imo) is to use Java 8 features of the Map interface
allocate a map
Iterate over the testPojoList
Map.compute will take a key, and then if the value is null, create one. Otherwise, it uses the existing value.
that value is returned and can be used in the same construct to further modify the value. In this case it does the following:
create a new TransformedTestPojo instance with the key (company) and new ArrayList<>() for the personal details.
then return that list and get the personal details list and add a new Personal details instance.
Map<String, TransformedTestPojo> map = new HashMap<>();
for (TestPojo tp : testPojoList) {
map.compute(tp.getCompany(),
(k, v) -> v == null ? new TransformedTestPojo(k,
new ArrayList<>()) : v)
.getPersonalDetailsList().add(new PersonalDetails(
tp.getName(), tp.getCity()));
}
Once the map has been created, get the map values (which has the TransformedTestPojo instances) and return as a collection.
Collection<TransformedTestPojo> collection = map.values();
Note that a Collection (super type of List) , not a List is created. If a list is required you can do the following.
List<TransformedTestPojo> list = new ArrayList<>(map.values());
Displaying the results
list.forEach(k -> {
System.out.println(k.getCompany());
k.getPersonalDetailsList()
.forEach(p -> System.out.println(" " + p));
});
prints
Tesla
[Mike, Denver]
[Bob, Atlanta]
[Steve, Chicago]
[John, Boston]
Here is a stream solution.
stream the testPojoList
Use Collectors.groupingBy with company as the key
The associated list will be of PersonalDetails instances.
then stream the entrySet of the map and build a list of TransformedTestPojo
List<TransformedTestPojo> list1 = testPojoList.stream()
.collect(Collectors.groupingBy(TestPojo::getCompany,
Collectors.mapping(
tp -> new PersonalDetails(
tp.getName(), tp.getCity()),
Collectors.toList())))
.entrySet().stream()
.map(e -> new TransformedTestPojo(e.getKey(),
e.getValue()))
.toList();
}
Note that the map itself could be used instead of a returned List<TransformedTestPojo>. The key is the company name and the value contains the list of PersonalDetails. If that is useful, then all you need is the following:
Map<String, List<PersonalDetails>> result = testPojoList.stream()
.collect(Collectors.groupingBy(TestPojo::getCompany,
Collectors.mapping(
tp -> new PersonalDetails(
tp.getName(), tp.getCity()),
Collectors.toList())))

DynamoDB C# cannot convert string to integer error

I created a DynamoDb using NET and able to getitem, which is not an empty list. I get a status 400 error on the putitem using Postman. This is the error:
"errors": {
"id": [
"Could not convert string to integer: 9134d3a0-a6bf-4409-87b3-d9fad02bd31c. Path 'id', line 2, position 44."
]
},
This is the body I use for the post:
{
"id":"9134d3a0-a6bf-4409-87b3-d9fad02bd31c",
"replyDateTime": "63669789320007900",
"body":"a good body",
"title":"best title",
"creator": " James"
}
This is my createtable code:
var request = new CreateTableRequest
{
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = "S"
},
new AttributeDefinition
{
AttributeName = "ReplyDateTime",
AttributeType = "S"
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = "HASH" // Partition Key
},
new KeySchemaElement
{
AttributeName = "ReplyDateTime",
KeyType = "Range" // Sort Key
}
},
this is the putitem code:
public async Task AddNewEntry(string id, string replyDateTime, string body, string title, string creator)
{
var queryRequest = RequestBuilder(id, replyDateTime, body, title, creator);
await PutItemAsync(queryRequest);
}
private PutItemRequest RequestBuilder(string id, string replyDateTime, string body, string title, string creator)
{
var item = new Dictionary<string, AttributeValue>
{
{"Id", new AttributeValue {S = id}},
{"ReplyDateTime", new AttributeValue {S = replyDateTime}},
{"Body", new AttributeValue {S = body}},
{"Creator", new AttributeValue {S = creator}},
{"Title", new AttributeValue {S = title}}
};
return new PutItemRequest
{
TableName = "BlogDynamoDbTable",
Item = item
};
}
private async Task PutItemAsync(PutItemRequest request)
{
await _dynamoClient.PutItemAsync(request);
}
}
I believe I made the primary key a string. Why is an integer even mentioned in the error message?
I found my error. The model file was defining id as an integer. Grrr
I changed it to string and it posts.
public class Item
{
[Amazon.DynamoDBv2.DataModel.DynamoDBHashKey]
public string Id { get; set; }
[Amazon.DynamoDBv2.DataModel.DynamoDBRangeKey]
public string ReplyDateTime { get; set; }
public string Body { get; set; }
public string Title { get; set; }
public string Creator { get; set; }
}

Joining 2 lists with condition

I want to join 2 lists. Students and Persons.
Both Student and Person has id and a name variable, plus Student has another variable called isStudying. I want to join all Students to Person with the isStudying variable.
var persons = new Person { id = 1, name = "John" };
var persons = new Person { id = 2, name = "Ace" };
var persons = new Person { id = 3, name = "Mike" };
var persons = new Person { id = 4, name = "Yob" };
var persons = new Person { id = 5, name = "Ken" };
var students = new Student { id = 2, name = "Ace", isStudying=true };
var students = new Student { id = 3, name = "Mike", isStudying = true };
var students = new Student { id = 5, name = "Ken", isStudying = true };
persons.Addrange(students.where(student.id.contain(persons.id)));
Here is full solution implemented in linq, used inheritance
class Person
{
public int id { get; set; }
public string name { get; set; }
}
class Student : Person
{
public bool isStudying { get; set; }
}
void Main()
{
var person1 = new Person { id = 1, name = "John" };
var person2 = new Person { id = 2, name = "Ace" };
var person3 = new Person { id = 3, name = "Mike" };
var person4 = new Person { id = 4, name = "Yob" };
var person5 = new Person { id = 5, name = "Ken" };
var persons = new List<Person> { person1, person2, person3, person4, person5 };
var student1 = new Student { id = 2, name = "Ace", isStudying = true };
var student2 = new Student { id = 3, name = "Mike", isStudying = true };
var student3 = new Student { id = 5, name = "Ken", isStudying = true };
var students = new List<Student> { student1, student2, student3 };
var personsRes = persons.Where(y => students.Select(x => x.id).Contains(y.id));
Console.WriteLine(personsRes);
}
Try This:
public class Person
{
public int id { get; set; }
public string name { get; set; }
}
public class Student
{
public int id { get; set; }
public string name { get; set; }
public bool isStudying { get; set; }
}
var persons = new List<Person> { new Person { id = 1, name = "John" },
new Person { id = 2, name = "Ace" },
new Person { id = 3, name = "Mike"},
new Person { id = 4, name = "Yob" },
new Person { id = 5, name = "Ken" } };
var students = new List<Student> { new Student { id = 2, name = "Ace", isStudying = true },
new Student { id = 3, name = "Mike", isStudying = true },
new Student { id = 5, name = "Ken", isStudying = true } };
var allPersons = (from p in persons
join s in students on new { first = p.id } equals new { first = s.id } into sjoin
from slj in sjoin.DefaultIfEmpty()
select new
{
id = p.id,
name = p.name,
isStudying = (slj != null ? (slj.isStudying ? "TRUE" : "FALSE") : string.Empty)
}).ToList();
For future readers' reference, one simple answer which I provided in comments using LINQ is:
With anonymous types:
persons.Select(p => new { p.id, p.name, students.Any(s => s.id == p.id && s.isStudying) });
Using a custom class (the Student class can actually be re-used):
persons.Select(p => new Student { id = p.id, name = p.name, isStudying = students.Any(s => s.id == p.id && s.isStudying) });

Dictionary int, myclass

That's my class
public class PersonelAtama
{
public int PersonelID { get; set; }
public int YonetimTalepID { get; set; }
public bool durum { get; set; }
}
I want to doDictionary<int,list<myclass>>
Dictionary<int, List<PersonelAtama>>
PersonelAtamaListesi = new Dictionary<int, List<PersonelAtama>>();
How to insert into the list
PersonelAtamaListesi.Add
How assignments are made
PersonelAtamaListesi[0][1]
PersonelAtamaListesi.Add(0,new PersonelAtama()
{
PersonelID = personelID,
YonetimTalepID = yonetimTalepID,
durum = false
});
assignment into the list and how to use again
I want to add to the list and component values to achieve. I want to sample code.
You have List as TValue so:
PersonelAtamaListesi.Add(0, new List<PersonelAtama>()
{
new PersonelAtama()
{
PersonelID = 1,
YonetimTalepID = 2,
durum = false
},
new PersonelAtama()
{
PersonelID = 11,
YonetimTalepID = 222,
durum = true
}
});