How to sort child HashMap in object - java

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());

Related

Find minimum common elements from array.

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
}

Sorting lists with one instance

Hello I am trying to pass to my jsp page two sorted Lists which I get from the database like that
#RequestMapping(value = "/sortDate", method= RequestMethod.GET)
public void sortedLists(Model model, HttpSession session){
List<Song> songsByDate;
try {
songsByDate = SongDAO.getInstance().getAllSongs();
Collections.sort(songsByDate, new UploadTimeComparator());
session.setAttribute("songs", songsByDate);
/////////////////////////////////
List<Song> songsByLikes;
try {
songsByLikes = SongDAO.getInstance().getAllSongs();
Collections.sort(songsByLikes, new LikesComparator());
session.setAttribute("songs2", songsByLikes);
}}}
However the problem is since I use getInstance() , songs and songs2 are the same Lists sorted by Likes,how can I overcome this problem?
You need to copy each "all songs" list to a new array list, which you can then proceed to sort.
So:
List<Song> songsByDate = new ArrayList<>( SongDAO.getInstance().getAllSongs() );
Collections.sort( songsByDate, new UploadTimeComparator() );
List<Song> songsByLikes = new ArrayList<>( SongDAO.getInstance().getAllSongs() );
Collections.sort( songsByLikes, new LikesComparator() );

Java List get last duplicate Object

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.

HashMap<String, ArrayList<String>>

I am trying to get HashMap store a String and a ArrayList<String>.
Basicly what I want is for the first String to be a Name, and the arraylist to contain every country the user have been to.
Example:
{Andrew, [USA, China]}
{Lola, [Sweden, Denmark]}
The problem I meet is whenever the user puts in a country, the country will be stored under both names:
"The HashMap contains: {Andrew=[USA, China, Sweden, Denmark], Lola=[USA, China, Sweden, Denmark]}"
ArrayList<String> namelist = new ArrayList<>();
ArrayList<String> test = new ArrayList<>();
ArrayList<String> archive = new ArrayList<>();
HashMap<String, ArrayList<String>> thearchive = new HashMap<>();
(input.equals("New Country")){
System.out.println("Name of the Person? ");
String name = in.nextLine();
if(namelist.contains(name)){
System.out.println("Which Country have you visited?");
String country = in.nextLine();
if (archive.contains(country)){
System.out.println("You've already visited this country.");
}
else {
test.add(country);
thearchive.put(name, country);
System.out.println("HashMap Contains: " + thearchive);
}
}
else{
System.out.println("The person does not exist please add first.");
}
Does someone knows why the HashMap is not storing the key/values the way I want too?
Your code is nota completed so I can't know what is test an thearchive. But let's create an example:
HashMap<String, ArrayList<String>> list = new HashMap<String, ArrayList<String>>();
ArrayList<String> anotherlist = new ArrayList<String>();
anotherlist.add("Brazil");
anotherlist.add("USA");
list.put("Augusto", anotherlist);
I hope it helps.
Usually your problem is due to re-using the same ArrayList for all people, so that all folks share the same Countries, all held by the one single ArrayList. A solution is to create a new ArrayList for each person -- meaning new ArrayList<String> needs to be inside some loop where you create your traveler's name String.
So for example, you could change your code to this:
ArrayList<String> namelist = new ArrayList<>();
ArrayList<String> test = new ArrayList<>();
// ArrayList<String> archive = new ArrayList<>();
HashMap<String, ArrayList<String>> arkivet = new HashMap<>();
(input.equals("New Country")){
System.out.println("Name of the Person? ");
String name = in.nextLine();
archive = ArrayList<String>(); // **********
arkivet.put(name, archive); // ************
if(namelist.contains(name)){
System.out.println("Which Country have you visited?");
String country = in.nextLine();
if (archive.contains(country)){
System.out.println("You've already visited this country.");
}
else {
test.add(country);
thearchive.put(name, country);
System.out.println("HashMap Contains: " + thearchive);
}
}
else{
System.out.println("The person does not exist please add first.");
}

Query.FilterOperator for different roles

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

Categories