It is not printing anything there is no error.
kindly help me in resolving his error.
I have tried three methods to print but still not a single one is working and there isn't any error.
import java.util.ArrayList;
public class JavaEight {
public static void main(String args[])
{
ArrayList<Employee> Emp = new ArrayList<>();
Employee e1 = new Employee(101, "Ravi", "Delhi", "2000");
Employee e2 = new Employee(102, "Vineet", "Mangalore", "5000");
Employee e3 = new Employee(103, "Punit", "Mumbai", "3000");
Employee e4 = new Employee(104, "Shruti", "Banglore", "6000");
Employee e5 = new Employee(105, "Ritu", "Hyderabad", "8000");
for(int i=0; i<Emp.size();i++)
{
Employee e = (Employee)Emp.get(i);
System.out.println(e);
}
Emp.forEach(i -> System.out.println(Emp));
for(Employee i : Emp)
{
System.out.println(Emp);
}
}
}
emp.add(e1); etc is missing
you have created the employee objects, but you did not add them to the list. thus the list is blank, and not printing anything
add Employee in your ArrayList.
ArrayList<Employee> Emp = new ArrayList<>();
Employee e1 = new Employee(101, "Ravi", "Delhi", "2000");
Employee e2 = new Employee(102, "Vineet", "Mangalore", "5000");
Employee e3 = new Employee(103, "Punit", "Mumbai", "3000");
Employee e4 = new Employee(104, "Shruti", "Banglore", "6000");
Employee e5 = new Employee(105, "Ritu", "Hyderabad", "8000");
Emp.add(e1);
Emp.add(e2);
Emp.add(e3);
Emp.add(e4);
Emp.add(e5);
hope , it will resolve your issue.
This is because your ArrayList Emp is empty.
You have created the Employee object but you have not added it to Emp.
add it to Emp like Emp.add(e1).
Related
I want to know if it is possible to write an object name in an input(Scanner or maybe another way?) through the console and then do something with it.
package test;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person p1 = new Person(1, "pedro");
Person p2 = new Person(2, "juan");
Person p3 = new Person(3, "diego");
ArrayList personList = new ArrayList();
personList.add(p1);
personList.add(p2);
//Something like this doesn't work :S
Person personToAdd = input.nextPerson();
personList.add(personToAdd);
}
}
for example in this case I wanna input the object name "p3" and then add it to the ArrayList, is there any way to do something like this?
List<Person> personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);
// you need to get each field you want to save with scanner
// nextLine/nextInt and so on to set other field
// e.q newPerson.setAge(<value from scanner>)
String personName = input.nexLine();
Person newPerson = new Person(personName);
personList.add(newPerson);
I have two query and resultsets, in the below code I want to showcase that for a particular userGroupCode I have certain userPreference and employee associated with it. I have written the code below code to display the userGroupCode object:
String query1= "SELECT ug.userGroupCode, ug.userGroupDesc, up.userPreference"
+ "FROM dbo.UserGroup_link ug INNER JOIN dbo.UserPreference up ON ug.userGroupCode = up.userGroupCode";
userGroupCode
userGroupDesc
userPreference
A100
Finance
Mumbai
A100
Finance
Bangalore
A200
Supply Chain
Chennai
A201
Marketing
Delhi
A201
Marketing
Kolkata
A300
Health
Indore
String query2= "SELECT ug.userGroupCode, ug.userGroupDesc, emp.employee_id,emp.name,emp.role"
+ "FROM dbo.UserGroup ug INNER JOIN dbo.employee emp ON ug.userGroupCode = emp.userGroupCode";
userGroupCode
userGroupDesc
employee_id
name
role
A100
Finance
101
Foo1
Developer
A100
Finance
101
Foo1
Team Lead
A200
Supply Chain
091
Test1
Manager
A201
Marketing
591
User1
Analyst
A201
Marketing
1001
Boo1
Scrum Master
A300
Health
1001
Boo1
Developer
I have class UserGroupMapping like:
public class UserGroupMapping {
private String userGroupCode;
private String userGroupCode;
private List<String> userPreference;
private List<Employee> emp;
//getter and setter
}
Another class for Employee is:
public class Employee {
private String employee_id;
private String name;
private List<String> role;
//getter and setter
}
In my stored procedure class I am calling these queries with the help of jdbcTemplate.query();
String userCode = null;
List<String> userPreferenceList = new ArrayList<>();
List<UserGroupMapping> userGroupMappingList = new ArrayList<>();
List<UserGroupMapping> userGroupMappingList1 = new ArrayList<>();
UserGroupMapping userGroupMapping = new UserGroupMapping();
List<Employee> employeeList = new ArrayList<>();
Employee emp = new Employee();
UserGroupMapping userGroupMapping1 = new UserGroupMapping();
jdbcTemplate.query(query1, (rs)->{
String user_group_code = rs.getString("userGroupCode");
String user_group_desc = rs.getString("userGroupDesc");
String user_preference = rs.getString("userPreference");
if(userCode == null){
userGroupMapping.setUserGroupCode(user_group_code);
userGroupMapping.setUserGroupDesc(user_group_desc);
userPreferenceList.add(userPreference);
userCode = user_group_code;
} else if (userCode.equals(user_group_code)) {
userPreferenceList.add(userPreference);
} else {
userGroupMapping.setUserPreference(userPreferenceList);
userGroupMappingList.add(userGroupMapping);
userPreferenceList = new ArrayList<>();
userGroupMapping = new userGroupMapping();
userGroupMapping.setUserGroupCode(user_group_code);
userGroupMapping.setUserGroupDesc(user_group_desc);
userPreferenceList.add(userPreference);
userCode = user_group_code;
}});
userCode = null;
userGroupMapping.setUserPreference(userPreferenceList);
userGroupMappingList.add(userGroupMapping);
jdbcTemplate.query(query2, (rs)->{
String user_group_code = rs.getString("userGroupCode");
String user_group_desc = rs.getString("userGroupDesc");
String emp_id = rs.getString("employee_id");
String name = rs.getString("name");
if(userCode == null){
userGroupMapping1.setUserGroupCode(user_group_code);
userGroupMapping1.setUserGroupDesc(user_group_desc);
emp.setId(employeeId);
emp.setName(name);
employeeList.add(emp);
userCode = user_group_code;
} else if (userCode.equals(user_group_code)) {
Employee emp = new Employee();
emp.setId(employeeId);
emp.setName(name);
employeeList.add(emp);
} else {
userGroupMapping1.setEmployee(employeeList);
userGroupMappingList1.add(userGroupMapping1);
employeeList = new ArrayList<>();
userGroupMapping1 = new userGroupMapping();
Employee emp = new Employee();
userGroupMapping1.setUserGroupCode(user_group_code);
userGroupMapping1.setUserGroupDesc(user_group_desc);
emp.setId(employeeId);
emp.setName(name);
employeeList.add(emp);
userCode = user_group_code;
}});
userGroupMapping1.setEmployee(employeeList);
userGroupMappingList1.add(userGroupMapping1);
List<UserGroupMapping> ugList = Stream.concat(userGroupMappingList.stream, userGroupMappingList1.stream).distinct().collect(Collectors.toList())
return ugList;
The problem is that I want my output to be like :
[
{
"userGroupCode" : "A100",
"userGroupDesc" : "Finance",
"userPreference": ["Mumbai","Bangalore"],
"Employee" : [
"employee_id" : "101",
"name" : "Foo1",
"role" : ["Developer","Team Lead"]
]
}
]
After merging the two list I am getting the below output:
[
{
"userGroupCode" : "A100",
"userGroupDesc" : "Finance",
"userPreference": ["Mumbai","Bangalore"],
"Employee" : []
},
{
"userGroupCode" : "A100",
"userGroupDesc" : "Finance",
"userPreference": [],
"Employee" : [
"employee_id" : "101",
"name" : "Foo1",
"role" : []
]
}
]
Could anyone please help me with few things:
How could I embed the role into the Employee object.
How can I merge the table based on userGroupCode and userGroupDesc.
I am feeling the code is not that performance optimised, How could I optimised this code.
Thank you in advance.
Ola,
You can group by using Map taking id as key and value as object ( to be aggregated into) . For example:
if(map.containes(key))
{
get object from map and do Ops.
}
else
{
1. Create new object
2. Do set Ops on Object
3. Add to map.
}
You basically have 2 solutions,
Write a query that returns all results with joins and do filtering in java, quite easy to achieve with 2 maps (one for the UserGroup the other for the Employee.
Write a query and aggregate the duplicates using list in the query itself.
SELECT ug.userGroupCode, ug.userGroupDesc, up.userPreference, emp.employee_id,emp.name,emp.role
FROM dbo.UserGroup_link ug
INNER JOIN dbo.UserPreference up ON ug.userGroupCode = up.userGroupCode
INNER JOIN dbo.employee emp ON ug.userGroupCode = emp.userGroupCode
Then use a RowCallbackHandler to achieve what you want (instead of a ResultSetExtractor.
Map<String, UserGroup> userGroups = new HashMap<>;
Map<Integer, Employee> employees = new HashMap<>;
jdbc.query(query, (rs) -> {
String userGroupCode = rs.getString("userGroupCode");
String emp_id = rs.getString("employee_id");
UserGroupMapping ugm userGroups.computeIfAbsent(userGroupCode, {
UserGroupMapping ugm1 = new UserGroupMapping();
ugm1.setUserGroupCode(userGroupCode);
ugm1.setUserGroupDesc(rs.getString("userGroupDesc");
ugm1.setUserPreference(new ArrayList<>());
ugm1.getEmployee(new ArrayList<>());
return ugm1;
});
ugm.getUserPreference().add(rs.getString("userPreference"));
Employee emp = employees.computeIfAbsent(emp_id, {
Employee emp1 = new Employee();
emp1.setName(rs.getString("name"));
emp1.setRole(new ArrayList<>());
ugm.getEmployee().add(emp);
return emp1;
});
emp.getRole().add(rs.getString("role"));
});
return userGroups.values();
The above code will get all UserGroupMapping objects from the result including all the Employee instances. The temporary maps are needed to determine if record has already been shown.
Another solution would be to use list in your query and some GROUP BY statement to let the query do part of the aggregation. That way you could make it a bit easier to create an Employee.
I am having 2 Employee List. One List contains the name and employeeId and the second List contains employeeId and mobile number. employee id is the primary key.
The requirement is to get the List which contains the id, Name, and mobile no using streaming.
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee emp1 = new Employee(101, "Shiv1");
Employee emp2 = new Employee(102, "Shiv2");
Employee emp3 = new Employee(103, "Shiv3");
Employee emp4 = new Employee(104, "Shiv4");
Employee emp5 = new Employee(101, 00001);
Employee emp6 = new Employee(101, 00002);
Employee emp7 = new Employee(101, 00003);
Employee emp8 = new Employee(101, 00004);
List<Employee> employeeNameList = new ArrayList<Employee>();
employeeNameList.add(emp1);
employeeNameList.add(emp2);
employeeNameList.add(emp3);
employeeNameList.add(emp4);
List<Employee> employeeMobileList = new ArrayList<Employee>();
employeeMobileList.add(emp5);
employeeMobileList.add(emp6);
employeeMobileList.add(emp7);
employeeMobileList.add(emp8);
employeeNameList.stream()
.filter(item -> item.getId() == 3)
.map(i -> i.setMobileNo(9089));
}
}
You can create a mapping of the empId to their name using the first list.
Map<Integer, String> empIdToName = employeeNameList.stream()
.collect(Collectors.toMap(Employee::getId, Employee::getName, (a, b) -> a));
Use such a mapping to create the objects further while iterating through the second and looking up this map, such as:
List<Employee> employees = employeeMobileList.stream()
.filter(item -> empIdToName.containsKey(item.getId()))
.map(i -> new Employee(i.getId(), empIdToName.get(i.getId()), i.getMobileNo()))
.collect(Collectors.toList());
I have a problem I want to create a new arraylist as have to send it other class .
I cannot post my original problem so copied the data.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Grouping {
List<Student> studlist1 = new ArrayList<Student>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1", "John", "New York"));
studlist.add(new Student("1", "Max", "California"));
studlist.add(new Student("2", "Andrew", "Los Angeles"));
studlist.add(new Student("3", "Michael", "New York"));
studlist.add(new Student("3", "Sam", "California"));
studlist.add(new Student("4", "Mark", "New York"));
Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
String key = student.stud_id;
if (groupedStudents.containsKey(key)) {
List<Student> list = groupedStudents.get(key);
list.add(student);
}
else {
List<Student> list = new ArrayList<Student>();
list.add(student);
groupedStudents.put(key, list);}
}
Set<String> groupedStudentsKeySet = groupedStudents.keySet();
int index = 0;
for (String id: groupedStudentsKeySet) {
List<Student> stdnts = groupedStudents.get(id);
for (Student student : stdnts) {
// Want to create a new arraylist as belows.Grouing data in arraylist according to same ID
// arraylist will be as
//
// index 0: 1,John,New York,Max,Califoornia
// index 1: 2, Andrew, Los Angeles
// index 2: 3,Michael, New York, "Sam", California
// index 3: 4,Mark, New York
}
}
}
}
class Student {
String stud_id;
String stud_name;
String stud_location;
Student(String sid, String sname, String slocation) {
this.stud_id = sid;
this.stud_name = sname;
this.stud_location = slocation;
}
}
Want to create a new arraylist as belows.Grouing data in arraylist according to same ID
Arraylist should be as
index 0: 1,John,New York,Max,Califoornia
index 1: 2, Andrew, Los Angeles
index 2: 3,Michael, New York, "Sam", California
index 3: 4,Mark, New York
Just want the same arraylist as above
if (groupedStudents.containsKey(key)) {
groupedStudents.get(key).add(student);
}
Use this code.
Hope this will help you.
I've suggested earlier to check 'groupingBy' methods in Stream Api(https://stackoverflow.com/questions/57236902/group-data-in-arraylist?noredirect=1#comment100976235_57236902), what you trying to do can be done in one line:
Map<String, List<Student>> collect = studlist.stream().collect(Collectors.groupingBy(Student::getStud_id));
It's not list by indexes, but I suppose its even more convenient.
Don't forget to add getter to your Student class.
I have the below results as part of resultset.
Name Dept
John IT
Mike IT
Cathy CS
Julie CS
Aria Electronics
Shann Electronics
I should be able to separate the resultset based on Dept and put the results in a map. E.g: After Mike, the dept changes and hence I should put John and Mike in a map. Then Cathy and Julie in a map and so on. How do I do it?
public void loadMap(ResultSet inputResultSet, MbGlobalMap inputTranslationObjMap) throws Exception {
String key = "";
List < dept > list = new ArrayList < dept > ();
while (inputResultSet.next()) {
String name = inputResultSet.getString(1);
String key = inputResultSet.getString(2);
dept d1 = new dept(name, key);
list.add(d1);
}
if (inputTranslationObjMap.containsKey(key)) {
inputTranslationObjMap.update(key, list);
} else {
inputTranslationObjMap.put(key, list);
}
}
Try something like this -
public void loadMap(ResultSet inputResultSet,
MbGlobalMap inputTranslationObjMap) throws Exception {
// String key = "";
List<dept> list = null;
while (inputResultSet.next()) {
String name = inputResultSet.getString(1);
String key = inputResultSet.getString(2);
// first check if the map has a list already.
if (inputTranslationObjMap.containsKey(key)) {
list = inputTranslationObjMap.get(key);
} else {
// No... add a new list to the map.
list = new ArrayList<dept>();
inputTranslationObjMap.put(key, list);
}
dept d1 = new dept(name, key);
list.add(d1);
}
}