Map to List , List to Map - list

class Person {
int? id;
String? name;
int? age;
Person(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
#override
String toString() {
return '{$id,$name,$age}'.toString();
}
static String PersonNameAge(name, age) {
name = name;
age = age;
return ('{$name,$age}');
}
}
void main(List<String> args) {
var per1 = Person(1, 'Mark', 15);
var per2 = Person(2, 'Jack', 24);
var list = [];
list.add(per1);
list.add(per2);
print(list);
var map1 = {};
list.forEach((element) {
map1[element.name] = element.age;
});
print(map1);
var list1 = [];
map1.forEach((name, age) => list1.add(Person.PersonNameAge(name, age)));
print(list1);
var map2 = {};
list1.forEach((element) {
map2[element.name] = element.age;
});
print(map2);
}
I'm new to Dart. Basically trying to convert Map to List and then Back to Map. Using the same logic but somehow it give me an error only on the last map2 section. Wanted to know what's the logical error in the map2 section .The foll is the error code:
Unhandled exception
Nosuchmethoderror: Class String has no instance getter name.
"

Related

build Map of Maps in java 8 from list of Objects

I need to convert a list of object into map of maps. I have tried to mock the problem statement in terms of student object. Any one to the rescue please. So teh problem is like below :
I have a list of Student object and I want to transform this into Map of Studentkey, Value is another map with key as DepartId Enum and value as count of departents. StudentKey is Object consist of studentId and Hno(some combination I need to use as a key to map). Departent is Enum. I have created it using java7, but not able to to so in Java 8. Can any one help please
public class Student {
private int Id;
private String name;
private Department dept;
private int hno;
...........
}
public enum Department {
ARTS,SCIENCE,MATHS,MUSIC
}
public class StudentKey {
private int Id;
private int hno;
.......
}
public class TestStudent {
public static void main(String[] args) {
Student st1= new Student(1, "Alex", Department.ARTS, 23);
Student st2= new Student(1, "Alex", Department.ARTS, 23);
Student st3= new Student(1, "Alex", Department.SCIENCE, 24);
Student st4= new Student(1, "Alex", Department.SCIENCE, 24);
Student st5= new Student(2, "John", Department.MUSIC, 25);
Student st6= new Student(2, "John", Department.MATHS, 26);
Student st7= new Student(2, "John", Department.MATHS, 26);
Student st8= new Student(3, "Doe", Department.MUSIC, 25);
Student st9= new Student(3, "Doe", Department.MATHS, 67);
List<Student> list = new ArrayList<>();
list.add(st1);
list.add(st2);
list.add(st3);
list.add(st4);
list.add(st5);
list.add(st6);
list.add(st7);
list.add(st8);
list.add(st9);
//buildMapinJava8(list);
Map<StudentKey, Map<Department, Long>> resultMap =buildMapinJava7(list);
printMap(resultMap);
}
private static Map<StudentKey, Map<Department, Long>> buildMapinJava7(List<Student> list) {
Map<StudentKey, Map<Department, Long>> resultMap = new HashMap<>();
for (Student student : list) {
StudentKey newKey = new StudentKey(student.getId(), student.getAge());
Map<Department, Long> deptMap= resultMap.get(newKey);
if(deptMap==null){
deptMap = new HashMap<>();
resultMap.put(newKey, deptMap);
}
Long count =deptMap.get(student.getDept());
count = count!=null?count:0;
deptMap.put(student.getDept(), count+1);
}
return resultMap;
}
private static Map<StudentKey, Map<Department, Long>> buildMapinJava8(List<Student> list) {
list.stream().collect(Collectors.toMap(new Function<Student, StudentKey>() {
#Override
public StudentKey apply(Student t) {
return new StudentKey(t.getId(), t.getAge());
}
}, new Function<Student, Map<Department, Long>>() {
#Override
public Map<Department, Long> apply(Student t) {
return null;//??? how to do here
}
}));
}
private static void printMap(Map<StudentKey, Map<Department, Long>> resultMap) {
for (Entry<StudentKey, Map<Department, Long>> entry : resultMap.entrySet()) {
System.out.print(entry.getKey().getId()+" , "+entry.getKey().getAge()+" ");
for(Entry<Department, Long> dept :entry.getValue().entrySet()){
System.out.println("department : "+dept.getKey()+" : "+dept.getValue());
}
}
}
}
Thanks #Holger,It worked. here is my code.
private static Map<StudentKey, Map<Department, Long>> buildMapInJava8(List<Student> list)
{
Map<StudentKey,Map<Department,Long>> map = list.stream()
.collect(Collectors.groupingBy(t -> new StudentKey(t.getId(), t.getAge()),
Collectors.groupingBy(Student::getDept, Collectors.counting())));
return map;
}

Get summary for multiple class fields in Java8 using map reduce technique

Below is Student class definition :
class Student{
String name;
int sub1;
int sub2;
int sub3;
// etc...etc...
}
I have list of all students.
Requirement is to get average of sub1, sub2 and sub3. And also get min mark and max mark in any subject for any student.
Below is the code for sub1:
IntSummaryStatistics sub1Summary = students.stream().collect(Collectors.summarizingInt(s -> s.sub1));
Is it possible to do with single expression or I will have to create IntSummaryStatisticsfor each subject and compare each lowest and highest subj value?
Thanks in advance
Try following :
List<Student> students = Arrays.asList(Student.create("A", 60, 55, 35),
Student.create("B", 40, 65, 75),
Student.create("C", 70, 45, 95));
Map<String, IntSummaryStatistics> subjectsSummary = new HashMap<String, IntSummaryStatistics>();
Map<String, List<Integer>> subjectMarks = new HashMap<String, List<Integer>>();
List<Integer> sub1Marks = new ArrayList<>();
List<Integer> sub2Marks = new ArrayList<>();
List<Integer> sub3Marks = new ArrayList<>();
// Input : Student
// Output : Map(Key=SubjectName, Value= List of Marks for students)
Function<Student, Map<String, List<Integer>>> toSubjectsMap = (s) -> {
sub1Marks.add(s.getSub1());
sub2Marks.add(s.getSub2());
sub3Marks.add(s.getSub3());
subjectMarks.put("Sub1", sub1Marks);
subjectMarks.put("Sub2", sub2Marks);
subjectMarks.put("Sub3", sub3Marks);
return subjectMarks;
};
//Function to generate summary stats from the list of integers/marks
Function<List<Integer>, IntSummaryStatistics> generateStatsFunc = (listOfMarks) -> {
return listOfMarks.stream().collect(Collectors.summarizingInt(marks->marks));
};
// 1. Students are mapped to generate Map for subject-->List of Marks
// 2. Doing flatMap on the generate Map to get the Keys from the map(list of subjects)
// 3. Collecting the Keys(Subject Names) of Map to Map(Key=SubjectName,Value=IntSummaryStats for Subject)
students.stream().map(toSubjectsMap).flatMap(subMap -> subMap.keySet().stream())
.collect(() -> subjectsSummary/* Initial Value of Map */, (summary, key) -> {
// Generate the stats from the list of marks for the subject
IntSummaryStatistics st = generateStatsFunc.apply(subjectMarks.get(key));
//Adding the stats for each Subject into the result Summary
summary.put(key, st);
} , (summary1, summary2) -> {
//merging the two maps
summary1.putAll(summary2);
});
System.out.println(subjectsSummary);
and Student class as follows :
class Student {
String name;
int sub1;
int sub2;
int sub3;
static Student create(String name, int sub1, int sub2, int sub3) {
// validation
return new Student(name, sub1, sub2, sub3);
}
public String getName() {
return name;
}
public int getSub1() {
return sub1;
}
public int getSub2() {
return sub2;
}
public int getSub3() {
return sub3;
}
private Student(String name, int sub1, int sub2, int sub3) {
this.name = name;
this.sub1 = sub1;
this.sub2 = sub2;
this.sub3 = sub3;
}
#Override
public String toString() {
return name;
}
}

Error on Spring REST webservice call

I have following webservice call
#RequestMapping(value = "modifyUser/{userDn}", method = RequestMethod.POST, headers="Accept=application/json")
public #ResponseBody
JSONObject modifyUser(#PathVariable String userDn, #RequestBody DirectoryUser directoryUser) {
// Modify User
boolean modifiedUser = this.authenticationService.modifyUser(userDn, directoryUser.getPassword(), directoryUser);
// Build JSONObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("modifyUser", modifiedUser);
return jsonObject;
}
I am using following client method to access above REST webservice.
String url = "http://www.local.com:8080/CommonAuth-1.0-SNAPSHOT/api/authentication/modifyUser/";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "user6.external")
JSONObject ob = new JSONObject();
ob.put("description", "updated");
System.out.println(ob.toString());
StringEntity entity = new StringEntity(ob.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
I always get "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method" error. What is wrong in my code. I am able to access other webservice calls without using #RequestBody and using simple path variables. The issue is with #RequestBody and how i am using HttpPost.
public class DirectoryUser {
private String displayName;
private String fullName;
private String userName;
private String firstName;
private String lastName;
private String description;
private String country;
private String company;
private String phone;
private String emailAddress;
private String password;
private boolean expirePassword = true;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isExpirePassword() {
return expirePassword;
}
public void setExpirePassword(boolean expirePassword) {
this.expirePassword = expirePassword;
}
}
JSON string i am posting is {"description":"updated"}
try {
/* your code */
if (httpResponse != null) {
InputStream in = httpResponse.getEntity().getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
System.out.println(out.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Can you check what the status code says? Also, please check if it is HTTPS.
By default Spring try to use Jackson for json marshall/unmarshall:
private static final boolean jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", WebMvcConfigurationSupport.class.getClassLoader()) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", WebMvcConfigurationSupport.class.getClassLoader());
you need to add Jackson libs to your project.

IList List is null in my Composition Class .. WHY?

I am usling IList List property to get a list of students class in University class .. as i try to access this list in department Class which is a part of university class .. the List is Null .. can anyone tell the reason?
namespace UniversitySystem
{
class University : CollectionBase
{
private string _uniName;
Departments _depart = new Departments();
public University(string un, string dn, string cp, List<Student> Slist)
{
this._uniName = un;
this.CED.DepartName = dn;
this.CED.ChairPerson = cp;
foreach (Student s in Slist)
{
List.Add(s);
}
}
#region properties
public string UniName
{
get { return _uniName; }
set { _uniName = value; }
}
public Departments CED
{
get { return _depart; }
set { _depart = value; }
}
#endregion
public class Departments : CollectionBase
{
private string _departName;
public string DepartName
{
get { return _departName; }
set { _departName = value; }
}
private string _chairPerson;
public string ChairPerson
{
get { return _chairPerson; }
set { _chairPerson = value; }
}
public List<Student> StudentListForCED = new List<Student>();
public Departments()
{
_departName = null;
_chairPerson = null;
StudentListForCED = null;
}
public Departments(string dn, string cp, List<Student> Slist)
{
this._departName = dn;
this._chairPerson = cp;
foreach (Student s in Slist)
{
List.Add(s);
}
}
public void showDetails()
{
Console.WriteLine("Departmental Info");
Console.WriteLine("DepartmentName: " + _departName);
Console.WriteLine("Chairperson Name: " + _chairPerson);
Console.WriteLine("Student Info:");
foreach (Student item in List)
{
Console.WriteLine("Name: " + item.Name);
Console.WriteLine("deptName: " + item.RegNo);
Console.WriteLine("total marks: " + item.TotalMarksObtained);
Console.WriteLine("percentage: " + item.GetPercentage());
}
}
}
}
}
THE main() part is
namespace UniversitySystem
{
class Program
{
static void Main(string[] args)
{
List<Student> slist = new List<Student>();
slist.Add(new Student("sana", 1234, "CIS", 650));
slist.Add(new Student("anam", 2345, "BCIT", 400));
slist.Add(new Student("fizzza", 2670, "Electrical", 670));
University u1 = new University("NED", "computer", "UKP", slist);
Console.WriteLine(u1.CED.DepartName);
u1.CED.showDetails();
}
}
}
The initializing code for University does not store the list you give it as a parameter.
try storing the list in a variable in either the department or the university object itself, and when you are showing the details for either of those object you can reference that list, the one you stored upon creating the object.
Hope that helps!
I made a couple changes that should work.
public Departments(string dn, string cp, List<Student> Slist)
{
this._departName = dn;
this._chairPerson = cp;
foreach (Student s in Slist)
{
StudentListForCED.Add(s);
}
}
public void showDetails()
{
Console.WriteLine("Departmental Info");
Console.WriteLine("DepartmentName: " + _departName);
Console.WriteLine("Chairperson Name: " + _chairPerson);
Console.WriteLine("Student Info:");
foreach (Student item in StudentListForCED)
{
Console.WriteLine("Name: " + item.Name);
Console.WriteLine("deptName: " + item.RegNo);
Console.WriteLine("total marks: " + item.TotalMarksObtained);
Console.WriteLine("percentage: " + item.GetPercentage());
}
}
Please read this a little more thoroughly.

Hibernate querying issue

I have the following code on the webservice that uses Hibernate
Session session = ICDBHibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.load(User.class, userid);
userId is a paramter sent from the client.
User class
package com.icdb.data;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class User implements java.io.Serializable {
private Integer userid;
private String username;
private String email;
private String password;
private String firstname;
private String lastname;
// private String streetaddress;
// private String city;
// private String phone;
private String state;
private String country;
private Date birthdate;
// private String zipcode;
private Set usersesForFavoriteuser = new HashSet(0);
private Set recipetipses = new HashSet(0);
private Set recipeses = new HashSet(0);
private Set recipepictureses = new HashSet(0);
private Set onlineuserses = new HashSet(0);
private Set generaltipses = new HashSet(0);
private Set usersesForFollowinguser = new HashSet(0);
private Set recipereviewses = new HashSet(0);
public User() {
}
public User( String username,
String password,
String email,
String firstname,
String lastname,
// String streetaddress,
// String city,
// String phone,
String state,
String country,
Date birthdate )
// String zipcode )
{
this.username = username;
this.password = password;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
// this.streetaddress = streetaddress;
// this.city = city;
// this.phone = phone;
this.state = state;
this.country = country;
this.birthdate = birthdate;
// this.zipcode = zipcode;
}
public User( String username,
String password,
String email,
String firstname,
String lastname,
// String streetaddress,
// String city,
String phone,
// String state,
// String country,
// String email,
Date birthdate,
// String zipcode,
Set usersesForFavoriteuser,
Set recipetipses,
Set recipeses,
Set recipepictureses,
Set onlineuserses,
Set generaltipses,
Set usersesForFollowinguser,
Set recipereviewses )
{
this.username = username;
this.password = password;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
// this.streetaddress = streetaddress;
// this.city = city;
// this.phone = phone;
this.state = state;
this.country = country;
this.birthdate = birthdate;
// this.zipcode = zipcode;
this.usersesForFavoriteuser = usersesForFavoriteuser;
this.recipetipses = recipetipses;
this.recipeses = recipeses;
this.recipepictureses = recipepictureses;
this.onlineuserses = onlineuserses;
this.generaltipses = generaltipses;
this.usersesForFollowinguser = usersesForFollowinguser;
this.recipereviewses = recipereviewses;
}
public Integer getUserid() {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
// public String getStreetaddress() {
// return this.streetaddress;
// }
// public void setStreetaddress(String streetaddress) {
// this.streetaddress = streetaddress;
// }
// public String getCity() {
// return this.city;
// }
// public void setCity(String city) {
// this.city = city;
// }
// public String getPhone() {
// return this.phone;
// }
// public void setPhone(String phone) {
// this.phone = phone;
// }
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthdate() {
return this.birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
// public String getZipcode() {
// return this.zipcode;
// }
// public void setZipcode(String zipcode) {
// this.zipcode = zipcode;
// }
public Set getUsersesForFavoriteuser() {
return this.usersesForFavoriteuser;
}
public void setUsersesForFavoriteuser(Set usersesForFavoriteuser) {
this.usersesForFavoriteuser = usersesForFavoriteuser;
}
public Set getRecipetipses() {
return this.recipetipses;
}
public void setRecipetipses(Set recipetipses) {
this.recipetipses = recipetipses;
}
public Set getRecipeses() {
return this.recipeses;
}
public void setRecipeses(Set recipeses) {
this.recipeses = recipeses;
}
public Set getRecipepictureses() {
return this.recipepictureses;
}
public void setRecipepictureses(Set recipepictureses) {
this.recipepictureses = recipepictureses;
}
public Set getOnlineuserses() {
return this.onlineuserses;
}
public void setOnlineuserses(Set onlineuserses) {
this.onlineuserses = onlineuserses;
}
public Set getGeneraltipses() {
return this.generaltipses;
}
public void setGeneraltipses(Set generaltipses) {
this.generaltipses = generaltipses;
}
public Set getUsersesForFollowinguser() {
return this.usersesForFollowinguser;
}
public void setUsersesForFollowinguser(Set usersesForFollowinguser) {
this.usersesForFollowinguser = usersesForFollowinguser;
}
public Set getRecipereviewses() {
return this.recipereviewses;
}
public void setRecipereviewses(Set recipereviewses) {
this.recipereviewses = recipereviewses;
}
}
also userId defined in the .hbm.xml as
<id name="userid" type="java.lang.Integer">
<column name="userid"/>
<generator class="identity"/>
</id>
So we have a table of users and another tables that its FK is userId.
I need to update the code to handle the request with a username - and then retrieve the userId instead of the mentioned code of the webservice.
Please help :)
Yoav
// I assume username is unique
// username is a parameter
// to get the full user object by name
String queryString = "from User where username = :username";
Query query = session.createQuery(queryString);
query.setString(":username", username);
User user = (User) query.uniqueResult();
// to get just the id
String queryString = "userid from User where username = :username";
Query query = session.createQuery(queryString);
query.setString(":username", username);
Integer userid = (Integer) query.uniqueResult();