I do have a User class which implements Comparable. After I add list of users into PriorityQueue<User> they should be prioritized by scores, but for some reason they don't. Could you please help me to figure out why users are not sorted in my Queue?
Update:
I am accessing queue by polling elements. prioritisedUsers.poll() it always comes with random scores with order respect.
PriorityQueue<User> prioritisedUsers = userPriorityStrategy.computeUserPriority(users);
while(!prioritisedUsers.isEmpty()){
System.out.println(prioritisedUsers.poll().getPriorityScore());
}
OUTPUT:
0.35036433736768735
0.6619121139678329
0.09520067929838127
0.4013591573863
0.6704568389588227
0.5989900926939181
0.7320779721160738
Thanks for any help!
public class User implements Comparable<User>{
private long id;
private String fistName;
private String lastName;
private double priorityScore;
public User (long id, String firstName, String lastName){
this.id = id;
this.fistName = firstName;
this.lastName = lastName;
}
public double getPriorityScore(){
return this.priorityScore;
}
public void setPriorityScore(double priorityScore){
this.priorityScore = priorityScore;
}
public long getId(){
return this.id;
}
public String getFistName(){
return this.fistName;
}
public String getLastName(){
return this.lastName;
}
public int compareTo(User o) {
return (int) (this.getPriorityScore() - o.getPriorityScore());
}
}
public PriorityQueue<User> computeUserPriority(List<User> users) {
PriorityQueue<User> prioritisedUsers = new PriorityQueue<User>(users.size());
for (User user : users) {
user.setPriorityScore(rand.nextDouble());
prioritisedUsers.add(user);
}
return prioritisedUsers;
}
I'm not so sure that your cast to (int) works well... because casting to an int implicitly drops any decimal.
If I'm not in wrong, try something like
public int compareTo(User object) {
if (this.getPriorityScore() < object.getPriorityScore())
return -1;
if (this.getPriorityScore() == object.getPriorityScore())
return 0;
return 1;
}
or alternatively and more simply:
public int compareTo(User o) {
return Double.compare(this.getPriorityScore(), o.getPriorityScore());
}
Related
Helper Class
public class HomeScreenChatsHelper implements Comparable {
private String ID;
private String Name;
private String Image;
private String From;
private String Seen;
private String LastMessage;
private String LastMessageTime;
public HomeScreenChatsHelper(){
}
public HomeScreenChatsHelper(String id, String name, String image, String from, String seen, String lastmessage, String lastMessageTime) {
this.ID=id;
this.Name = name;
this.Image = image;
this.From = from;
this.Seen = seen;
this.LastMessage = lastmessage;
this.LastMessageTime = lastMessageTime;
}
public String getID() {
return ID;
}
public void setID(String id) {
ID = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getMessage() {
return LastMessage;
}
public void setMessage(String message) {
LastMessage = message;
}
public String getTime() {
return LastMessageTime;
}
public void setTime(String time) {
LastMessageTime = time;
}
public String getFrom() {
return From;
}
public void setFrom(String from) {
From = from;
}
public String getSeen() {
return Seen;
}
public void setSeen(String seen) {
Seen = seen;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int compareTo(Object comparestu) {
long compareage= Long.parseLong(((HomeScreenChatsHelper)comparestu).getTime());
long a = Long.parseLong(LastMessageTime);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
}
return Long.compare(a,compareage);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HomeScreenChatsHelper)) return false;
HomeScreenChatsHelper that = (HomeScreenChatsHelper) o;
return getID().equals(that.getID());
}
#Override
public int hashCode() {
return getID().hashCode();
}
Activity
for(HomeScreenChatsHelper str : mChats) {
if (str.getID().equals(ID)) {
mChats.remove(ID);
break;
}
}
There are a ton of tutorials on how to do it and I've spent the past week looking for a solution and I still don't have it. Is there anyway I can remove an whole object by just specifying just the ID? I wont have the values of all the other fields so I just want to remove a particular object by its ID. Also I cant use the clear option because I need the other data. So can someone help me out please?
With the present code nothing happens. No errors but doesn't work
By using java-8 you can filter the list, result will be the List<HomeScreenChatsHelper> that does have HomeScreenChatsHelper with same id
List<HomeScreenChatsHelper> mChats = new ArrayList<>();
//filter
List<HomeScreenChatsHelper> result = mChats.stream()
.filter(str->!str.getId().equals(Id)).
.collect(Collectors.toList());
Or by using Iterator
// Iterator.remove()
Iterator itr = mChats.iterator();
while (itr.hasNext())
{
HomeScreenChatsHelper x = itr.next();
if (x.getId().equals(Id)) }
itr.remove();
}
}
Your question is quite unclear. is mChats a List containing HomeScreenChatsHelper objects?
I assume so. If this is the case, then you can change your foreach loop into the normal loop
//Assuming mChats is List e.g ArrayList
for (int i = 0; mChats.size(); i++){
if (mChats.get(i).getID().equals(ID)) {
mChats.remove(i);
break;
}
}
The easiest way in Java 8 or later is with Collection#removeIf:
mChats.removeIf(str -> str.getID().equals(ID));
By the way, the convention in Java is for fields to begin with a lowercase letter.
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java
public enum Packets {
// Maps enums to integers 0-3
PACKET_NONE = 0, PACKET_SYNC,
PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,
// Maps enums to integers 13-16
PACKET_FILL = 13, PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}
I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).
In Java you can assign values to Enum if that's what you are looking for. It will look like this:
public enum Packets {
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3);
private int value;
Packets(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
Now you can call enum like this to get it's value:
Packets.PACKET_SYNC.getValue(); //It will return 1
You can add a field to your enum, intialize this field in the enumeration constant's constructor call and then return this field from a public getter. This should look about like this:
public enum Packets
{
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3),
PACKET_FILL(13),
PACKET_GLASS(14),
PACKET_FILLI(15),
PACKET_GLASSI(16);
private final int id;
private MyEnum(final int id) {
this.id = id;
}
public final int getId() {
return index;
}
}
This is not that clean of a solution but if you really want to auto-initialize them to increment the same way the C++ declaration does, without explicitly defining each individual ID, you can do something like this:
public enum Packets
{
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3),
PACKET_FILL(13),
PACKET_GLASS(),
PACKET_FILLI(),
PACKET_GLASSI();
private int id;
private Packets(int id) {
this.id = id;
}
private Packets(){
this.id = -1;
}
public final int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
public static void initIds(){
for(Packets p : Packets.values()){
if(p.getId()==-1){
if(p.ordinal()==0){
p.setId(0);
}else{
p.setId(Packets.values()[p.ordinal()-1].getId()+1);
}
}
}
}
}
Then you call the initialize and it will fill in the ID's for you:
Packets.initIds();
System.out.println(Packets.PACKET_AVAIL_1.getId()); //3
System.out.println(Packets.PACKET_GLASS.getId()); //13
System.out.println(Packets.PACKET_FILL.getId()); //14
System.out.println(Packets.PACKET_FILLI.getId()); //15
edit/addition:
If you move the code from the initIds()method into a static initializer block, you do not need the initialize call somewhere in your code:
public enum Packets {
PACKET_NONE(0),
PACKET_SYNC(1),
PACKET_EXPECT_TO_RECEIVE(2),
PACKET_AVAIL_1(3),
PACKET_FILL(13),
PACKET_GLASS(),
PACKET_FILLI(),
PACKET_GLASSI();
static {
for (Packets p : Packets.values()) {
if (p.getId() == -1) {
if (p.ordinal() == 0) {
p.setId(0);
} else {
p.setId(Packets.values()[p.ordinal() - 1].getId() + 1);
}
}
}
}
private int id;
private Packets(int id) {
this.id = id;
}
private Packets() {
this.id = -1;
}
public final int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
I have a POJO class A with the below structure
class A{
private String var1;
private int var2;
private String var3;
}
I have two ArrayList<A> List1 and List2 with different size. I want to remove all elements in List1 which are already present in List2 and this equality needs to be checked with respect to the value stored in var2.
I have already checked making the List a Hashset and using removeAll(). But this wont give the desired output since for the same var2, var1 values differ.
Please help me solve this problem.
Edit 1 - Requested by Murat
public class HistoryDto implements Serializable,Comparable<HistoryDto> {
private Integer id;
private String sId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSId() {
return sId;
}
public void setSId(String sId) {
this.sId = sId;
}
public String getTrackName() {
return trackName;
}
public void setTrackName(String trackName) {
this.trackName = trackName;
}
public String getTrackDescription() {
return trackDescription;
}
public void setTrackDescription(String trackDescription) {
this.trackDescription = trackDescription;
}
public Integer getUsedNo() {
return usedNo;
}
public void setUsedNo(Integer usedNo) {
this.usedNo = usedNo;
}
public String getExtraInfo() {
return extraInfo;
}
public void setExtraInfo(String extraInfo) {
this.extraInfo = extraInfo;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getPartyId() {
return partyId;
}
public void setPartyId(Integer partyId) {
this.partyId = partyId;
}
private String trackName;
private String trackDescription;
private Integer usedNo;
private String extraInfo;
private String imageUrl;
private Integer partyId;
public int compareTo(HistoryDto other) {
return this.sId.compareTo(other.sId);
}
}
Removing Items
ListA.removeAll(new HashSet(listB));
You need 2 loops nested.
pseudocode:
for each in A do
for each in B do
if (current item of A equals to current item of B)
say yes!
done
done
You just need to translate it to Java.
You may do it using the Stream API:
Set<Integer> var2 = list2.stream()
.map(a -> a.var2)
.collect(Collectors.toSet());
list1.stream()
.filter(a -> !var2.contains(a.var2))
.collect(Collectors.toList());
I'm trying to do this exercise: i have a student that has a name,surname and a number, i want to order the students by number..if i want to order by name or surname it seems easy but with number i don't know how to do..
this is my code:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
return name.compareTo(otherObject.getName());
}
}
//TESTER
ArrayList<Student> list = new ArrayList<Student>();
System.out.print("\n ORDER BY NUMBER \n");
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
String std = s.getAll();
System.out.println(std);
}
You can implement something like:
public int compareTo(Student otherObject) {
return Integer.compare(this.number, otherObject.getNumber());
}
So why you number is an int you can substract the number and return the difference:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
return number - otherObject.getmatricola();
}
}
Try doing this...should work
//CompareTo Name
public int compareTo(Student otherObject) {
if( this.getmatricola() > otherObject.getmatricola())
return 1;
else
return -1;
}
I am studying java by myself and I want to get help on exercise which i am doing myself.
The class is called Product which used for representing a product that a small company sells.
It should be possible to store the following information about each product.
The class should have the following methods:
A constructor
A method that returns the units of items in store
A method for deliverance to the store (increases the units of this product)
A method for withdrawal from the store (decreases the units of this product)
Please note that if one of the methods changes the stored items below the order point a message should be printed. It should also be impossible to have a negative amount of items.
I HAVE PROBLEM WITH METHODS. PLEASE TAKE A LOOK MY CODE AND GIVE ME SOME HINTS. I WILL APPRECIATE ALL RESPONDS.
THANK YOU.
Here is my program:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units, String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
unitsInStore = unitsInStore + store;
return unitsInStore ++ ;
}
public int withdrawal(int store){
unitsInStore = store - unitsInStore;
return unitsInStore --;
}
}
The deliveranceToStore method isn't correct. Why are you calling the method recursively?
The method can simply be:
public int deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
return unitsInStore;
}
If there is no need to return the number of units in store with this call, you should have the return type as void (i.e., if updating the count is sufficient):
public void deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
}
For withdrawal, you need a similar strategy where unitsInStore is updated:
public void withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
}
}
You can also make the withdrawal method return a boolean which tells whether the withdrawal action was successful. The method, in that case, may look like:
public boolean withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
return true;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
return false;
}
}