Removing full object from a value - java

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.

Related

How to get row from TableView?

I am creating a lobby application which will show all groups on a java tableview. Users are able to join groups that have space in them, else they will not be able to join.
I have been able to create this but I would like to be able to colour the row of the groups that have space in them in green and groups that are full will be coloured in red.
I will provide my code for this below. I am getting NullPointerException, which i dont know why. Thanks.
private void visualGroupAvailability() {
boolean isThereSpace;
for (currentGroupsModel o : groupsTable.getItems()) {
TableRow<currentGroupsModel> currentRow = getTableRow(o.getGroupID());
int limit = o.getNumberOfUsers();
isThereSpace = checkSpaceInGroup(o);
if(isThereSpace) {
currentRow.setStyle("-fx-background-color: #" + "388e3c ");
} else {
currentRow.setStyle("-fx-background-color: #" + "ffcdd2 ");
}
}
}
private TableRow<currentGroupsModel> getTableRow(int rowIndex) {
Set<Node> tableRowCell = groupsTable.lookupAll(".table-row-cell");
TableRow<currentGroupsModel> row = null;
for (Node tableRow : tableRowCell) {
TableRow<currentGroupsModel> r = (TableRow<currentGroupsModel>) tableRow;
row = r;
}
return row;
}
public class currentGroupsModel {
String groupName, groupDescription, hostName, groupType;
Integer numberOfUsers, groupID;
public currentGroupsModel(String gName, String gDesc, String hostName, String groupType, Integer numberOfUsers, Integer groupID){
this.groupName = gName;
this.groupDescription = gDesc;
this.hostName = hostName;
this.groupType = groupType;
this.numberOfUsers = numberOfUsers;
this.groupID = groupID;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDescription() {
return groupDescription;
}
public void setGroupDescription(String groupDescription) {
this.groupDescription = groupDescription;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getGroupType() {
return groupType;
}
public void setGroupType(String groupType) {
this.groupType = groupType;
}
public Integer getNumberOfUsers() {
return numberOfUsers;
}
public void setNumberOfUsers(int numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public Integer getGroupID(){
return this.groupID;
}
public void setGroupID(Integer newID){
this.groupID = newID;
}
}
This question cannot really be answered with what you have given us. It is hard looking for a NullPointerException if there is a currentGroupModel we know nothing about and there are constant red hairings. For example why do you store something in limit, you never use it! Why do you pass getTableRow a rowIndex, that you are never using? As far as I get it your getTableRow returns the last TableRow in the table, not a specific one. Please consider fixing those problems first, before eventually providing some code to understand the inner workings of your currentGroupModel.

How do I remove objects from an arraylist which are present in another arraylist based on one member variable of the object in Java?

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

Why is the sort method not working on this custom AbstractList implementation?

Android Studio is giving me a "Usage of API documented as #since 1.8+" error on the sort() line, inside the addAll() method. I'm not quite sure what this means...
All I want to do is a custom List where I can sort the List by the publishedAt property of Articles_Map.
AbstractArticlesList:
public class AbstractArticlesList extends AbstractList<Articles_Map> {
private final List<Articles_Map> l;
public AbstractArticlesList() {
l = new ArrayList<>();
}
public Articles_Map get(int index) {
return l.get(index);
}
public Articles_Map set(int index, Articles_Map element) {
Articles_Map oldValue = l.get(index);
l.add(index, element);
return oldValue;
}
public int size() {
return l.size();
}
private void doAdd(Articles_Map another) {
l.add(another);
}
public void addAll(List<Articles_Map> others) {
for (Articles_Map a : others) {
doAdd(a);
}
l.sort(byPublishedAtComparator);
}
private final Comparator<Articles_Map> byPublishedAtComparator =
new Comparator<Articles_Map>() {
#Override
public int compare(Articles_Map o1, Articles_Map o2) {
if (o1.publishedAt == null) {
return (o2.publishedAt == null) ? 0 : -1;
} else if (o2.publishedAt == null) {
return 1;
}
return o1.publishedAt.compareTo(o2.publishedAt);
}
};
}
Articles_Map:
public class Articles_Map {
public final String title;
public final String description;
public final String url;
public final String urlToImage;
public final Date publishedAt;
public Articles_Map(String title, String description, String url, String urlToImage, Date publishedAt) {
this.title = title;
this.description = description;
this.url = url;
this.urlToImage = urlToImage;
this.publishedAt = publishedAt;
}
}
sort() is new to API Level 24 (Android 7.0), courtesy of Android starting to adopt bits of Java 1.8.
Use Collections.sort() if your minSdkVersion is lower than 24.

Assign one json value for two fields in java using GSON

I am trying to assign the value returned by some function to a field in the deserialized class of json.
FileInfo.java
public class FileInfo {
#SerializedName("Name")
private String mName;
#SerializedName("Url")
private String mUri;
#SerializedName("Size")
private Integer mSize;
#SerializedName("ModTime")
private Long mModifiedTime;
private FileType mType;
#SerializedName("Children")
private ArrayList<FileInfo> mChildren = new ArrayList<>();
public ArrayList<FileInfo> getChildren() {
return mChildren;
}
public long getModifiedTime() {
return mModifiedTime;
}
public String getName() {
return mName;
}
public Integer getSize() {
return mSize;
}
public String getUrl() {
return mUri;
}
public FileType getType() {
return mType;
}
public void setChildren(ArrayList<FileInfo> mChildren) {
this.mChildren = mChildren;
}
public void setModifiedTime(long mModifiedTime) {
this.mModifiedTime = mModifiedTime;
}
public void setName(String mName) {
this.mName = mName;
}
public void setSize(Integer mSize) {
this.mSize = mSize;
}
public void setType(FileType mType) {
this.mType = mType;
}
public void setUri(String mUri) {
this.mUri = mUri;
}
#Override
public String toString() {
return FileInfo.class.toString();
}
public FileInfo() {
}
}
The mType needs to be assigned to foo(mName). I looked up custom deserializers and instance creators but none of those helped. I also thought of TypeAdapters which i feel defeats the purpose of keeping deserialization(using GSON) simple.
This is a sample JSON string that will be deserialized.
[
{
"Name":"Airport",
"Url":"http://192.168.2.2/api/sites/Baltimore%20Airport/Airport",
"Size":0,
"ModTime":"2015-12-02T14:19:17.29824-05:00",
"Children":null
}
]
P.S. I'm not sure if this should be done during deserialization but trying anyways. Also please let me know of alternative ways to achieve this.

How does Spring Data (MongoDB) read an object?

I am currently working on a project using the Spring framework and SpringData MongoDB (v.1.6.1 RELEASE). I now want to add a property to a stored object, that would simplify its retrieval, but I need to compute this property based on the state of the object at the point of time I want to save it. I tried to put that computation within the getter method of the object, but somehow SpringData is not using the getter to access the property.
The concrete example is the following:
I am storing events in the database and the events are allowed to span over several dates, creating a multi-date event. The events are defined by a start date (LocalDateTime) and an end date (LocalDateTime). I now want to store the information, if the event is a multi-date event or not, within the database. Concluding I added a boolean variable to the event (multiDate). Within the getter (isMultiDate) I am comparing the start and end date and returning true or false (depending on the dates).
My event object:
public class Event
{
#Id
private String id;
#NotBlank
private String name;
private String description;
private String location;
private double locationLat;
private double locationLog;
#NotNull
#JsonIgnore
private int startDateDayOfMonth, startDateMonth, startDateYear, startDateHour, startDateMinute;
#NotNull
#JsonIgnore
private int endDateDayOfMonth, endDateMonth,endDateYear, endDateHour, endDateMinute;
#LastModifiedDate
private Date lastChanged;
#Transient
private LocalDateTime startDateTime;
#Transient
private LocalDateTime endDateTime;
private boolean multiDate;
#DBRef
#NotEmpty
private List<Division> invitedDivision;
public Event() {}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getLocation()
{
return location;
}
public void setLocation(String location)
{
this.location = location;
}
public double getLocationLat()
{
return locationLat;
}
public void setLocationLat(double locationLat)
{
this.locationLat = locationLat;
}
public double getLocationLog()
{
return locationLog;
}
public void setLocationLog(double locationLog)
{
this.locationLog = locationLog;
}
public int getStartDateDayOfMonth()
{
return startDateDayOfMonth;
}
public void setStartDateDayOfMonth(int startDateDayOfMonth)
{
this.startDateDayOfMonth = startDateDayOfMonth;
}
public int getStartDateMonth()
{
return startDateMonth;
}
public void setStartDateMonth(int startDateMonth)
{
this.startDateMonth = startDateMonth;
}
public int getStartDateYear()
{
return startDateYear;
}
public void setStartDateYear(int startDateYear)
{
this.startDateYear = startDateYear;
}
public int getStartDateHour()
{
return startDateHour;
}
public void setStartDateHour(int startDateHour)
{
this.startDateHour = startDateHour;
}
public int getStartDateMinute()
{
return startDateMinute;
}
public void setStartDateMinute(int startDateMinute)
{
this.startDateMinute = startDateMinute;
}
public int getEndDateDayOfMonth()
{
return endDateDayOfMonth;
}
public void setEndDateDayOfMonth(int endDateDayOfMonth)
{
this.endDateDayOfMonth = endDateDayOfMonth;
}
public int getEndDateMonth()
{
return endDateMonth;
}
public void setEndDateMonth(int endDateMonth)
{
this.endDateMonth = endDateMonth;
}
public int getEndDateYear()
{
return endDateYear;
}
public void setEndDateYear(int endDateYear)
{
this.endDateYear = endDateYear;
}
public int getEndDateHour()
{
return endDateHour;
}
public void setEndDateHour(int endDateHour)
{
this.endDateHour = endDateHour;
}
public int getEndDateMinute()
{
return endDateMinute;
}
public void setEndDateMinute(int endDateMinute)
{
this.endDateMinute = endDateMinute;
}
public Date getLastChanged()
{
return lastChanged;
}
public void setLastChanged(Date lastChanged)
{
this.lastChanged = lastChanged;
}
public LocalDateTime getStartDateTime()
{
startDateTime = LocalDateTime.of(startDateYear, startDateMonth, startDateDayOfMonth, startDateHour, startDateMinute);
return startDateTime;
}
public void setStartDateTime(LocalDateTime startDateTime)
{
this.startDateTime = startDateTime;
if(startDateTime != null)
{
startDateYear = startDateTime.getYear();
startDateMonth = startDateTime.getMonthValue();
startDateDayOfMonth = startDateTime.getDayOfMonth();
startDateHour = startDateTime.getHour();
startDateMinute = startDateTime.getMinute();
}
}
public LocalDateTime getEndDateTime()
{
endDateTime = LocalDateTime.of(endDateYear, endDateMonth, endDateDayOfMonth, endDateHour, endDateMinute);
return endDateTime;
}
public void setEndDateTime(LocalDateTime endDateTime)
{
this.endDateTime = endDateTime;
if(endDateTime != null)
{
endDateYear = endDateTime.getYear();
endDateMonth = endDateTime.getMonthValue();
endDateDayOfMonth = endDateTime.getDayOfMonth();
endDateHour = endDateTime.getHour();
endDateMinute = endDateTime.getMinute();
}
}
public List<Division> getInvitedDivision()
{
return invitedDivision;
}
/**
* The function is setting all invited divisions, but is optimizing the set by eliminating unnecessary divisions.
* #param invitedDivision
*/
public void setInvitedDivision(List<Division> invitedDivision)
{
if(invitedDivision != null)
{
this.invitedDivision = DivisionManagementController.getOptimizedSetOfDivisions(invitedDivision);
} else
{
this.invitedDivision = invitedDivision;
}
}
public void addDivision(Division division)
{
if(invitedDivision == null)
{
invitedDivision = new ArrayList<>();
}
invitedDivision.add(division);
}
public boolean isMultiDate()
{
return (startDateDayOfMonth != endDateDayOfMonth) || (startDateMonth != endDateMonth) || (startDateYear != endDateYear);
}
public void setMultiDate(boolean multiDate)
{
this.multiDate = multiDate;
}
}
What am I getting wrong? Why is SpringData not using the public getter to access a private variable? (I actually returned always true and the database still only showed storing false).
Thanks in advance!
I am still not clear about the issue, but try this
public boolean isMultiDate()
{
multiDate = (startDateDayOfMonth != endDateDayOfMonth) || (startDateMonth != endDateMonth) || (startDateYear != endDateYear);
return multiDate;
}

Categories