This question already has answers here:
Comparator.comparing(...) of a nested field
(4 answers)
Closed 4 years ago.
In Java 8 Comparator, we can create a comparator as follows.
Comparator.comparing(keyExtractor);
Currently I have a class as follows
class Employee {
String name;
Department dept;
}
class Department {
String departmentName;
}
Now, if I want to create a comparator for Employee class which sorts the records based on the department name, how can I write my key extractor?
Tried the below code, but did not work.
Comparator.comparing(Employee::getDept::getDepartmentName);
You can use function that extracts a sort key
I.e.
Comparator.comparing(Employee::getDept,Comparator.comparing(Department::departmentName));
The trick here is method references are not objects and don't have members to access. So you can't do this:
Employee::getDept.getDepartmentName
Moreover, method references are not classes, so you can't get another method reference from them. So this also fails.
Employee::getDept::getDepartmentName
Finally, the only option that is left with us is this.
e -> e.getDept().getDepartmentName()
Try this out,
Employee empOne = new Employee("Mark", new Department("Accounts"));
Employee empTwo = new Employee("Melissa", new Department("Sales"));
List<Employee> employees = Arrays.asList(empOne, empTwo);
employees.sort(Comparator.comparing(e -> e.getDept().getDepartmentName()));
employees.forEach(System.out::println);
Related
This question already has answers here:
Remove object from ArrayList with some Object property
(5 answers)
Remove objects from an ArrayList based on a given criteria
(10 answers)
How to remove specific object from ArrayList in Java?
(17 answers)
Closed 1 year ago.
I have a class with its own hashCode() method. I am adding this class to a HashSet. How can I remove an item by its hashCode, without knowing the object itself?
For example, if I have the following code
HashSet<Data> set = new HashSet<>();
set.add(new Data(10, 5));
...
class Data {
public int importantVal;
public int notImportantVal;
//... constructor ...
#Override
public int hashCode() {
return importantVal;
}
}
and I knew the importantVal of a Data object, but not the object itself. How would I remove it? set.remove(10) does not work.
Best solution I can think of is to also override equals() to return if importantVal is the same, and then do set.remove(new Data(10, anyPlaceholderValue))
This question already has answers here:
Default constructor vs. inline field initialization
(5 answers)
Closed 3 years ago.
I have a class like:
public class TemplateFileResponse {
private String path;
private List<FileView> children;
}
I want to create an instance and set children is empty array. so what is the best way to do it?
You can create an empty list with the new operator:
public class TemplateFileResponse {
private String path;
private List<FileView> children = new ArrayList<>();
}
You may also want to initialize the path field, either in a constructor or inline, because otherwise it will be initialized to null by default.
I suggest that you read a tutorial about Java classes, constructors, methods, and instantiating objects to understand how all of this works.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Overall goal is to create a library simulation that allows searches for books as well as transactions eg to borrow a book. I've only included the parts I think are relevant.
I have the array stock in the Biblio class as follows:
public class Biblio{
private ArrayList<Book> stock;
and the Book class with the constructor:
public Book(String author , String title)
{
this.author = author;
this.title = title ;
code = null;//this is a String
}
In the main method I am trying to search for a Book object using the code (which is String), I am using the findCode method in the Biblio class:
public Book findCode(String searchedCode){
Book foundBook = null;
for(Book bookObj : stock){
if(bookObj.getCode().equxals(searchedCode)){
bookObj= foundBook;}//
return foundBook;
}
and here is the code in the main method I currently have:
Biblio libSim;
libSim = generateLib();
...
System.out.println(libSim.findCode(scan.next()));
but the output is coming up as null and I think it is because the foundBook equals null. However I can't return bookObj.
I do not know how I can find an object in an array by searching for the code variable. The books are added to the library in another method and using a setter method I have set any code that equals null to a string with the format LIB0001, this is done before I call the findCode method.
How do you find an object by searching the array for a specific instance variable?
You cannot compare Strings with ==
see here on how to do it properly: How do I compare strings in Java?
This question already has answers here:
Sorting a list of points with Java [duplicate]
(4 answers)
How do I use Comparator to define a custom sort order?
(9 answers)
Closed 9 years ago.
I have an objects class that holds the properties title, director, genre, rating. I have created an arraylist and have filled it with instances of this base class
ArrayList<Movie> movieCatalog
I am wanting to sort this ArrayList in alphabetical order by the title property and change their positions within the ArrayList. From my research I understand I need to use a Comparator class but I am confused about how to do this.
You can create a custom comparator and than call the Collections.sort(movieCatalog,comparator); method.
E.g.
public static final Comparator<movieCatalog> movieComparator = new Comparator<movieCatalog>() {
public int compare(movieCatalog a1, movieCatalog a2) {
return a1.name.compareTo(a2.name);
}
};
Collections.sort(movieCatakig,movieComparator);
Your Movie class needs to implement Comparable<Movie>. Then you need to implement the compareTo method, which in this case can just call the String class compareTo method.
int compareTo(Movie other) {
return this.title.compareTo(other.title);
}
After that, if movies is an ArrayList of movies, you can simply do
Collections.sort(movies);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java ArrayList remove duplicates
From follwing class and list ,I need a list where name and date same and other should get remove .
from below list I need only first two records , because name and date are same third one should be delete.Could some one help me out.
public class TestBean {
public String name;
public Date birthDate;
public String city;
}
List<TestBean> list = new ArrayList<TestBean>();
TestBean testBean=new TestBean();
testBean.setName("test");
testBean.setBirthDate(new SimpleDateFormat("mm/dd/yyyy").parse("01/01/1981"));
testBean.setCity("chicago");
TestBean testBean1=new TestBean();
testBean.setName("test");
testBean.setBirthDate(new SimpleDateFormat("mm/dd/yyyy").parse("01/01/1981"));
testBean.setCity("newyork");
TestBean testBean2=new TestBean();
testBean.setName("test");
testBean.setBirthDate(new SimpleDateFormat("mm/dd/yyyy").parse("01/01/1982"));
testBean.setCity("chicago");
list.add(testBean);
list.add(testBean1);
list.add(testBean2);
Override equals() (based on name and birth date) and hashCode() for TestBean class and then add all the objects to Set data structure. Set filters duplicate objects provided you have equals() overridden correctly.