Sorting List<> in Java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a List<Person>. Person's attributes are String name, String secondName, int phoneNum.
How can I sort this List by the String property secondName?
I've tried moving into another List<String> the data from the previous list moving secondName to the first position, then applying Collection.sort and creating other List<Person> with the data of the List sorted but its too complicated.

Java 8 introduced a sort method in the List interface which can use a comparator.
If you have a getter for secondName you can do this:
myList.sort(Comparator.comparing(Person::getSecondName));
If you don't have a getter use this one:
myList.sort(Comparator.comparing((person)->(person.secondName)));
for more ways and answers:
link

Lets assume here is your Pojo Class Person.
class Person{
String name;
String secondName;
//Getter and setters
}
Then sort the list by java collection API itself.
java.util.Collections.sort(personList, new Comparator<Person>() {
#Override
public int compare(Person o1, Person o2) {
return o1.getSecondName().compareToIgnoreCase(o2.getSecondName());
}
});

Related

How to sort array of objects in Java by alphabet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have class Library
public class Books extends Library {
String regNumber
String author;
String name;
int yearOfPublishing;
String publishingHouse;
int numberOfPages;
public Books(String regNumber, String author, String name, int yearOfPublishing,
String publishingHouse, int numberOfPages) {
this.regNumber = regNumber;
this.author = author;
this.name = name;
this.yearOfPublishing = yearOfPublishing;
this.publishingHouse = publishingHouse;
this.numberOfPages = numberOfPages;
}
How to list books with authors' last names in alphabetical order?
First, you should have a Book class for individual books. Assuming your Library is a list of books you can then do it like this.
List<Book> sortedLibrary = library.stream()
.sorted(Comparator.comparing(book -> book.author))
.collect(Collectors.toList());
Since no details were provided about the author name field it sorts on the entire field whether its first, last or both names.
If you want to sort them in place, a cleaner approach would be.
library.sort(Comparator.comparing(book->book.author));

How to create a new List<A> from an existing List<B> using lambda without function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an existing List of type "A". I want to create a new list of type "B" from this list. Class "B" shares some common fields with Class "A" as shown in the example below. preferably, I like to avoid using any function calls from the lambda.
public class A{
int quantity;
String description;
int refNumber;
Date timeStamp;
}
public class B{
int quantity;
String description;
}
Thanks
I have two solution for you without using stream.map but both of them look ugly and I would recommend a proper and clean solution with a map function.
List<BObject> listB = list.stream().collect(Collectors.mapping(a -> new BObject(a.quantity, a.description), Collectors.toList()));
or
List<BObject> listB = list.stream().collect(ArrayList::new, (listBa, a) -> listBa.add(new BObject(a.quantity, a.description)), ArrayList::addAll);
Now let's compare solutions above to this:
List<BObject> listB = list.stream().map(BObject::new).collect(Collectors.toList());
or this
List<BObject> listB = list.stream().map(a -> new BObject(a.quantity, a.description)).collect(Collectors.toList());
I think the last two versions look much better but require additional constructors in BObject class

Setters on objects Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hello so I'm having a bit of difficulties with a setter method on objects.
public class Company {
private String companyName;
public static int numberOfEmployees;
public Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
Employees employee1 = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());
employees[numberOfEmployees] = employee1;
numberOfEmployees++;
}
So basicly this is a method defined in the 'company class' while making an Employees object who's using the parameters for making a 'Programmer'.
But that's not the deal, what I want tot do is by calling this setter method, automaticly create an object. So each time it's used, kind of increment the name of the object it's going to make.
So for example the first time I use it it makes an object called Employee1 and stores it in Employee[0].. second time I want it to store Employee2 into Employee[1].
Maybe I'm making this way too difficult but I'm just trying things out, and can't seem to find a way to make this work.
I suppose that Programmer object is subclass of Employees, or else it will not work. More or less it should look like the following:
public class Company {
private String companyName;
public static int numberOfEmployees;
public static Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
numberOfEmployees++;
employees[numberOfEmployees] = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());;
}

Is there any way to crate arraylists based on a counter? Java/Android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
addDealership("BestWheels", "Deventer", arraylist1);
addDealership("HighDealerz", "Amsterdam", arraylist2);
addDealership("RoyalDealers", "Den Haag", arraylist3);
This is what I need to end up with. When the user presses the "add" button I need to add a new dealership which will have inside an array with cars. I need to be able to add/remove cars from the arrays, so I need some way to identify each one in particular.
So far my method looks like this:
private static void addDealership(String name, String city, ArrayList<Car> carArrayList) {
dealerships.add(new Dealership(name, city, carArrayList));
carArrayCounter++;
}
I basically want to modify my "addDealership" method to create separate arraylists for each dealership and then be able to add/remove elements.
Using Arraylist is a requirement, so I can't really use a HashMap although it would be a better option.
Solved using #ronginat 's suggestion.
Add a getCarList in Your Dealership class that returns the list's reference.
You can work with that reference to use List methods get and remove.
Implement public boolean equals(Object obj) in your Car class.
Your IDEA can help with auto generate this method.
Then you'll be able to remove a Car from a dealership's carList.
carList.remove(carObject);
You can use a HashMap instead of an ArrayList to access you methods. As a key you could use the name for example (could be something else, but must be unique). the advantage of a HashMap is that it is made for specific element access, unlike an ArrayList.
HashMap<String, DealerShip> dealerShip = new HashMap<String, DealerShip>();
private static void addDealerShip(String name, String city, ArrayList<Car> carArrayList) {
dealerShip.put(name, new DealerShip(name, city, carArrayList);
}
private static DealerShip getDealerShip(String name) {
return dealerShip.get(name);
}
Using Java 8. To identify the relevant Dealership:
final List<Dealership> dealerships = /* initialise dealerships */
//Find a dealership by name
final Dealership foundByName = dealerships.stream()
.filter(dealership -> dealership.name().equals("Name Of Dealership"))
.findAny()
.orElse(null);
//Find a dealership by name and then update its list of cars
dealerships.stream()
.filter(dealership -> dealership.name().equals("Name Of Dealership"))
.findAny()
.map(Dealership::carArrayList)
.ifPresent(cars -> {
//Update list of cars for that dealership here. For example...
cars.add(new Car());
})

Java - refering to an object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm new in Java and I'm trying to create a social network. I have a array of objects "People" which their names, e-mails and so on. I would like to create relations between them (like 'friends') so that program would connect two object.
I though about doing another array inside of every "Person" object, so each person would have a name, e-mail and friend array with all friends inside of it. I don't know how to refer to an other object of type People inside of object of this type.
I don't know if it's clear..
Hope it is!
Thank You in advance!
Here's one way:
public class Person {
private String name;
private String email;
private List<Person> friends;
// Leave the rest for you.
public void addFriend(Person p) {
if (p != null) {
this.friends.add(p);
}
}
public void removeFriend(Person p) {
this.friends.remove(p);
}
public boolean isFriend(Person p) {
return this.friends.contains(p);
}
}
You'll want constructors and a way to add and remove Person from your friend List.

Categories

Resources