Requirements:
User user1=new User("001","mama","hyd",new String[]{"java","spring","bootStrap"});
User user2=new User("002","gugu","mumbai",new String[]{"java","spring","hibernate"});
User user3=new User("003","lali","pune",new String[]{"angularjs"});
User user4=new User("004","asu","kashmir",new String[]{"java"});
List<User> list1=new ArrayList<User>();
list1.add(user1);
list1.add(user2);
list1.add(user3);
list1.add(user4);
o/p: user1,user2,user4 (having minimum one common skill e.g java)
Is there any possible way to do it?
The following code finds the largest set of users that share at least one skill:
User user1 = new User("001", "mama", "hyd", new String[]{"java", "spring", "bootStrap"});
User user2 = new User("002", "gugu", "mumbai", new String[]{"java", "spring", "hibernate"});
User user3 = new User("003", "lali", "pune", new String[]{"angularjs"});
User user4 = new User("004", "asu", "kashmir", new String[]{"java"});
List<User> list1 = new ArrayList<User>();
list1.add(user1);
list1.add(user2);
list1.add(user3);
list1.add(user4);
// convert the list of users into a map of skills to users with that skill
Map<String, List<User>> skillsMap = new HashMap<>();
for (User user : list1) {
for (String skill : user.getSkills()) {
skillsMap.computeIfAbsent(skill, (key) -> new ArrayList<>()).add(user);
}
}
// find the largest list of users with a skill
List<User> mostUsers = null;
for (List<User> usersWithSkill : skillsMap.values()) {
if (mostUsers == null || usersWithSkill.size() > mostUsers.size()) {
mostUsers = usersWithSkill;
}
}
// print the ids of the users in the largest user list
for (User user : mostUsers) {
System.out.println(user); // assumes there is a valid toString() method for User
}
Related
I need to implement sorting, but I have problems. I have class User and inside I have HashMap with address. At the moment I don't understanding how to sort child instance with Comparator
Map<String, String> address = new HashMap<>();
address.put("1", "firstAddress");
address.put("2", "secondAddress");
address.put("3", "thirdAddress");
User firstUser = new User(1, "Viktor", "0500000000", address);
User secondUser = new User(2, "Sergey", "0600000000", address);
User thirdUser = new User(3, "Vladimir", "0700000000", address);
List<User> users = new ArrayList<>();
users.add(firstUser);
users.add(secondUser);
users.add(thirdUser);
List<User> sortedUser = users.stream().sorted(user -> {
return user.getAddress() <-- How to sort address?
}).collect(Collectors.toList());
sortedUser.forEach(System.out::println);
I think this should sort your users by addresses (natural order).
List<User> sortedUser = users.stream().sorted((user1,user2)->
user1.getAddress().get(user1.getId()).compareTo(user2.getAddress().get(user2.getId()))).collect(Collectors.toList());
I have a list of Objects which is filled dynamically and I want to keep only the last duplicated Object. I tried the HashSet to remove duplicates but it's not doing big thing in my case.Can anyone help with this ?
My User Object shown below:
public class User {
public int id,score
public String firstName, lastName;
Getters and Setters ...
}
class getLasDuplicate {
public static void main(String[] args) {
List<User> a = new ArrayList<User>();
User u = new User();
u.setId(1);
u.setScore(2);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(1);
u.setScore(3);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(1);
u.setScore(4);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(2);
u.setScore(3);
u.setFirstName("kaos");
u.setLastName("family");
a.add(u);
User u = new User();
u.setId(1);
u.setScore(3);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(2);
u.setScore(2);
u.setFirstName("kaos");
u.setLastName("family");
a.add(u);
for(User us: a){
System.out.println( "Name:"+us.getFirstName +" "+us.getLastName+", Score:"+us.getScore()+", Id:"+us.getId());
}
}
In this case I want to find by Id the duplicated Objects and get only the last Object of duplicated ones in the List, so if I print the final List content I want to have something like this:
Name: Mike Jordon, Score: 3, Id: 1
Name: kaos family, Score: 2, Id: 2
If List is your input and you want to get last duplicates, you can try converting it to Map and change it back to List again as below:
Map<Integer, User> amap = new HashMap<Integer, User>();
for(User i: a){
amap.put(i.getId(), i); //when duplicate User with same Id is added, new User value will replace old one.
//So Id will always be mapped to last User with that Id
}
List<User> newA = new ArrayList(amap.values());
Then printing newA should give you intended result.
Here i'm able to get User Screen names and printing with the below code,but how can i sort those name alphabatically.
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
String name = (String) request.getSession().getAttribute("name");
long cursor = -1;
IDs ids = twitter.getFollowersIDs(name, cursor);
do {
for (long id : ids.getIDs()) {
User user = twitter.showUser(id);
out.println(user.getName());
}
} while ((cursor = ids.getNextCursor()) != 0);
This is my code where i'm getting names,how can i sort names.Thank for your help.
Actually a Comparator may be more than you need, I got mixed up with your previous question.
You can simply collect the names themselves in a list and then sort, e.g.:
...
final List<String> names = new LinkedList<String>();
do {
for (...) {
...
names.add(user.getName());
}
} while (...);
Collections.sort(names)
If you inspect names, it will now be sorted.
I am new to programming world, and i love it.
I have some problem on Query.Filter Operator by different roles.
Admin - Admin can view all leave history
Supervisor - Supervisor can view own and all employee under he/she
Employee - Employee only able to view own leave history
From the testing i has done. Admin and Employee is working fine and the problem I has faced is Supervisor, Supervisor able to view employee under he/she but unable to view own leave history.
here are part of the code, appreciate anyone can help me. Thank you
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.debug(ViewHistory.class);
DataTableModel dataTableModel = DataTablesUtility.getParam(request);
String regionSelected = request.getParameter("cri_region");
String sEcho = dataTableModel.sEcho;
int iTotalRecords = 0; // total number of records (unfiltered)
int iTotalDisplayRecords = 0; //value will be set when code filters companies by keyword
JsonArray data = new JsonArray(); //data that will be shown in the table
String emailAddress = (String)request.getSession().getAttribute("emailAdd");
Boolean isAdmin = false;
Boolean isSupervisor = false;
AdministratorService as = new AdministratorService();
for(Administrator admin : as.getAdministrators()){
if(admin.getEmailAddress().equalsIgnoreCase(emailAddress)){
isAdmin = true;
}
}
SupervisorService ss = new SupervisorService();
for(Supervisor s : ss.getSupervisors()){
if(s.getEmailAddress().equalsIgnoreCase(emailAddress)){
isSupervisor = true;
}
}
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query(History.class.getSimpleName());
// only admin can view all leave history
if(!isAdmin && !isSupervisor){
Filter emailFilter = new FilterPredicate("emailAdd",
FilterOperator.EQUAL,
emailAddress);
Filter regionFilter = new FilterPredicate("region",
FilterOperator.EQUAL,
StringUtils.defaultString(regionSelected, "Singapore"));
Filter filter = CompositeFilterOperator.and(emailFilter, regionFilter);
q.setFilter(filter);
}
else if(!isAdmin && isSupervisor){
List<String> list = new ArrayList<String>();
EmployeeService es = new EmployeeService();
for(Employee emp : es.getEmployees()){
if(emailAddress.equalsIgnoreCase(emp.getSupervisor())){
list.add(emp.getEmailAddress());
}
}
// if some one under this supervisor
if(list != null && !list.isEmpty()){
Filter filter = new FilterPredicate("emailAdd",
FilterOperator.IN,
list);
q.setFilter(filter);
}
else{
// if not one under this supervisor , put update it self to avoid illegal argument
Filter filter = new FilterPredicate("emailAdd",
FilterOperator.EQUAL,
emailAddress);
q.setFilter(filter);
}
}
List<History> historyList = new LinkedList<History>();
List<History> entityList = new LinkedList<History>();
EDIT: Updated suggestion.
If currently for a supervisor you are able to correctly get the list of all employees who have him as the supervisor, then just add the supervisor's email also to the list which you will be using as a filter for querying leave history. So after finding the list of employee emails, also add:
list.add(emailAddress); //since emailAddress will be the email of the supervisor
Let's say i have a listbox that contain ten items, and then i set five items for every page, so now the listbox have two pages
and the problem is everytime i want to get the value in listbox it only get five items instead ten items.
im using ListItemRenderer on My Listbox
below is my code :
AnnotationConfiguration config = new AnnotationConfiguration();
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
String str = "from Users";
Query q = session.createQuery(str);
List<Users> user = q.list();
session.close();
sessionFactory.close();
list.setModel(new ListModelList<Users>(user));
list.setItemRenderer(new ListitemRenderer() {
#Override
public void render(Listitem item, Object data, int index)
throws Exception {
Users user = (Users) data;
item.setValue(user);
new Listcell(user.getUsername()).setParent(item);
new Listcell(user.getUserrole()).setParent(item);
}
});
}
below my code to get the value :
String name ="";
String role ="";
Users user = new Users();
Listbox box = (Listbox) list.getFellow("win").getFellow("list");
List<Listitem> lists = box.getItems();
//membaca setiap row yang ada pada list
for(Listitem currentList : lists){
List<Component> com = currentList.getChildren();
//membaca setiap column pada row
for (Component currentComp : com){
Listcell lc = (Listcell) currentComp;
if(lc.getColumnIndex() == 0){
name = lc.getLabel();
System.out.println("name = " + name);
}
if(lc.getColumnIndex()==1){
role = lc.getLabel();
System.out.println("role = " + role);
}
}
}
This is the correct behavior. The List is the View and the View
never has more then 5 Items as you discribed.
You want to get the Model so get the Model.
ListModelList lists = (ListModelList)box.getModel();