Get Duplicates Objects from ArrayList - java

How can I get duplicates from an ArrayList?
public class Order {
private String portId;
private String action;
private String idType;
private String id;
private BigDecimal amount;
public String getPortId() {
return portId;
}
public void setPortId(String portId) {
this.portId = portId;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}
My code:
List<Order> duplicateList = new ArrayList<Order>();
List<Order> nonDuplicateList = new ArrayList<Order>();
Set<Order> set = new HashSet<Order>();
for (Order order : listContainingAllOrders) {
if (!set.add(order)) {
duplicateList.add(order);
} else {
nonDuplicateList.add(order);
}
}
I want to achieve duplicateList and nonDuplicateList, where I will combine both the duplicate list and Non duplicate List together
and display on the UI. The duplicate Orders will be Identified by Error Message column.

If I understand you, then you could replace this
if (!set1.add(order)) {
with
if (!set1.contains(order)) {
set1.add(order);
Edit
You need to Override equals() and hashCode() in your Order. Assuming that Order(s) with the same id are equal by definition - one possible way would be,
#Override
public boolean equals(Object obj) {
if (obj instanceof Order) {
if (id == null) {
// return ((Order) obj).id == null;
return false; // probably best to prevent null
}
return id.equals(((Order) obj).id);
}
return false;
}
#Override
public int hashCode() {
return id.hashCode();
}

Related

Problem java Set data replaced/wiped on add

I have actually a problem on a Set in my project (code below)
public static Set<BeanObject> mapToSetBean(Collection<Object> listModel) {
Set<BeanObject> listToReturn = new HashSet<>();
for (Iterator<Object> iterator = listModel.iterator(); iterator.hasNext();) {
Object model = iterator.next();
BeanObject bean = new BeanObject();
bean = mapToBean(model);
listToReturn.add(bean);
}
return listToReturn;
}
When some beans are added to the list they replace another one.
For example:
List{}
add object1 / List{object1}
add object2 / List{object1, object2}
add object1 / List{object1, object2, object3}
add object4 / List{object4, object2, object3}
The equals and the hashcode of the object are override the hashcode are all different and in debug mode we don't enter in the override equals.
When I use an ArrayList everything works but I prefer not to change the type it has a huge impact on my project.
---------------- EDIT ---------------
public static BeanObject mapToBean(Object model) {
BeanObject bean = new BeanObject();
if (model != null) {
bean.setId(model.getId());
if(model.getId() != null){
bean.setIdString(model.getId().toString());
}
if (model.getName() != null) {
bean.setName(model.getName().toLowerCase());
}
bean.setActif(model.getActif());
if (model.getShortName() != null) {
bean.setShortName(model.getShortName().toUpperCase());
}
}
return bean;
}
BeanObject
public class BeanObject implements Comparable<BeanObject> {
/**
* serial
*/
private static final long serialVersionUID = 1L;
private BigInteger id;
private String name;
private String shortName;
private Short actif;
private String idString;
public BeanObject() {
}
public BeanObject(BigInteger id, String libelle) {
this.id = id;
this.name = libelle;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof BeanObject)) {
return false;
}
BeanObject other = (BeanObject) o;
boolean result;
if (null == this.id) {
if (null == other.id) {
result = true;
} else {
result = false;
}
} else {
result = this.id.equals(other.id);
}
return result;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
return this.id.intValue() * name.hashCode() * shortName.hashCode();
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public Short getActif() {
return actif;
}
public void setActif(Short actif) {
this.actif = actif;
}
public String getIdString() {
return idString;
}
public void setIdString(String idString) {
this.idString = idString;
}
}
Are you certain the BeanObject's hashcode values are unique? That hashcode method seems like it would map a lot of objects to 0 if any of its fields hashed to 0 since it is straight multiplication. I would suggest updating to a more standardized approach for it like the following:
#Override
public int hashCode() {
return Objects.hash(id, name, shortName);
}
Objects.hash is from the java.util package.
If this still doesn't solve the problem, I would double check the hashcode results for each bean object at add time.

Get value from java lang object on hibernate

I have query:
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
return (List<InvoiceItems>) session.createQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id").list();
}
InvoiceItems.java:
package id.co.keriss.consolidate.ee;
import java.util.Date;
import org.jpos.ee.Accounts;
public class InvoiceItems {
private long record_id;
private String id;
private String type;
private String invoice_id;
private Accounts account_record_id;
private Tenant tenant_record_id;
private String description;
private long amount;
private Date created_date;
private String usage_name;
private String plan_name;
private String account_id;
public String getAccount_id() {
return account_id;
}
public void setAccount_id(String account_id) {
this.account_id = account_id;
}
public long getRecord_id() {
return record_id;
}
public void setRecord_id(long record_id) {
this.record_id = record_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInvoice_id() {
return invoice_id;
}
public void setInvoice_id(String invoice_id) {
this.invoice_id = invoice_id;
}
public Accounts getAccount_record_id() {
return account_record_id;
}
public void setAccount_record_id(Accounts account_record_id) {
this.account_record_id = account_record_id;
}
public Tenant getTenant_record_id() {
return tenant_record_id;
}
public void setTenant_record_id(Tenant tenant_record_id) {
this.tenant_record_id = tenant_record_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
public String getUsage_name() {
return usage_name;
}
public void setUsage_name(String usage_name) {
this.usage_name = usage_name;
}
public String getPlan_name() {
return plan_name;
}
public void setPlan_name(String plan_name) {
this.plan_name = plan_name;
}
}
then set to an variable:
List<InvoiceItems> invoiceItems = invoiceItemsDao.findAllBalance(jsonRecv.getString("externalkey"));
I want to get the value from that query, what I try:
LogSystem.info(request, "List : " + invoiceItems.get(0).getId();
I got an error "can't cast to InvoiceItems"
then I try changing from List<InvoiceItems> to just List
get with this :
LogSystem.info(request, "List : " + invoiceItems.get(0);
but the output like this not the value:
[Ljava.lang.Object;#41ea9df8
any advice? final result what i want is calculate amount of tenant
session.createQuery take HQL (Hibernate query language) however I see you use native SQL. Try using createSQLQuery method.
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
Query query = session.createSQLQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id");
query.setResultTransformer(Transformers.aliasToBean(InvoiceItems.class));
List<InvoiceItems> list = query.list();
return list;
}

show all list query java hibernate

i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
public class TransactionQR implements Serializable {
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..

unique constraint Exception (SQLIntegrityConstraintViolationException)

I am trying to insert data in oracle DB using spring JPA repositories
I have a hash map which contains all the values which needs to be populated into DB,I am Iterating each value and setting into my Entity class
Basically I have a table which has a composite primary key(NotifiedToId).when I am setting the values ints throwing constraint violation exception.In my logs it is printing all correct values but its not getting inserted,
My Entity class:
#Embeddable
public class TbBamiNotifUserLogPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="NOTIFIED_TO_ID")
private String notifiedToId;
public TbBamiNotifUserLogPK() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getNotifiedToId() {
return this.notifiedToId;
}
public void setNotifiedToId(String notifiedToId) {
this.notifiedToId = notifiedToId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TbBamiNotifUserLogPK)) {
return false;
}
TbBamiNotifUserLogPK castOther = (TbBamiNotifUserLogPK)other;
return
this.notifRefNo.equals(castOther.notifRefNo)
&& this.notifiedToId.equals(castOther.notifiedToId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.notifRefNo.hashCode();
hash = hash * prime + this.notifiedToId.hashCode();
return hash;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="TB_BAMI_NOTIF_USER_LOG")
#NamedQuery(name="TbBamiNotifUserLog.findAll", query="SELECT t FROM TbBamiNotifUserLog t")
public class TbBamiNotifUserLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TbBamiNotifUserLogPK id;
#Column(name="NOTIF_CAT")
private String notifCat;
#Column(name="NOTIFIED_TO_NAME")
private String notifiedToName;
#Column(name="NOTIFIED_TO_ROLE")
private String notifiedToRole;
public TbBamiNotifUserLog() {
}
public TbBamiNotifUserLogPK getId() {
return this.id;
}
public void setId(TbBamiNotifUserLogPK id) {
this.id = id;
}
public String getNotifCat() {
return this.notifCat;
}
public void setNotifCat(String notifCat) {
this.notifCat = notifCat;
}
public String getNotifiedToName() {
return this.notifiedToName;
}
public void setNotifiedToName(String notifiedToName) {
this.notifiedToName = notifiedToName;
}
public String getNotifiedToRole() {
return this.notifiedToRole;
}
public void setNotifiedToRole(String notifiedToRole) {
this.notifiedToRole = notifiedToRole;
}
}
#Entity
#Table(name="TB_BAMI_NOTIFICATION_LOG")
#NamedQuery(name="TbBamiNotificationLog.findAll", query="SELECT t FROM TbBamiNotificationLog t")
public class TbBamiNotificationLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="\"ACTION\"")
private String action;
#Column(name="NOTIF_CONTENT")
private String notifContent;
#Column(name="NOTIF_TYPE")
private String notifType;
#Column(name="NOTIFIED_DATE_TIME")
private Timestamp notifiedDateTime;
private String refno;
#Column(name="\"VERSION\"")
private BigDecimal version;
public TbBamiNotificationLog() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public String getNotifContent() {
return this.notifContent;
}
public void setNotifContent(String notifContent) {
this.notifContent = notifContent;
}
public String getNotifType() {
return this.notifType;
}
public void setNotifType(String notifType) {
this.notifType = notifType;
}
public Timestamp getNotifiedDateTime() {
return this.notifiedDateTime;
}
public void setNotifiedDateTime(Timestamp notifiedDateTime) {
this.notifiedDateTime = notifiedDateTime;
}
public String getRefno() {
return this.refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public BigDecimal getVersion() {
return this.version;
}
public void setVersion(BigDecimal version) {
this.version = version;
}
}
Business Logic:
for (Entry<String, PushNotificationDetails> entry : finalTemplate.entrySet()){
try{
notificationlog.setNotifRefNo("121323");
notificationlog.setRefno(refNum);
notificationlog.setVersion(new BigDecimal(1));
notificationlog.setAction(action);
LOGGER.debug("TEMPLATE TYPE"+entry.getValue().getTemplate_type());
LOGGER.debug("TEMPLATE"+entry.getValue().getTemplate());
notificationlog.setNotifType(entry.getValue().getTemplate_type());
notificationlog.setNotifContent(entry.getValue().getTemplate());
notificationlog.setNotifiedDateTime(notifiedDateTime);
tbBamiNotifyLogRepository.save(notificationlog);
LOGGER.debug("inside if block ::: ");
LOGGER.debug("USERID is: "+entry.getValue().getUserID());
LOGGER.debug("NOTIFCAT is: "+entry.getValue().getNotif_cat());
LOGGER.debug("NOTIFUSER is: "+entry.getValue().getUserName());
LOGGER.debug("NOTIFROLE is: "+entry.getKey());
tbBamiNotifUserLogPK.setNotifiedToId(entry.getValue().getUserID());
tbBamiNotifUserLogPK.setNotifRefNo("121323");
tbBamiNotifUserLog.setId(tbBamiNotifUserLogPK);
LOGGER.debug("GET is: "+tbBamiNotifUserLog.getId().getNotifiedToId());
tbBamiNotifUserLog.setNotifCat(entry.getValue().getNotif_cat());
tbBamiNotifUserLog.setNotifiedToName(entry.getValue().getUserName());
tbBamiNotifUserLog.setNotifiedToRole(entry.getKey());
tbBamiNotifyUserLogRepository.save(tbBamiNotifUserLog);
}
Try to add notificationlog = new TbBamiNotificationLog() in the beginning of your saving for. It could be possible when you try to save the second row but the instance is the same (with id provided during the first save).

How to sort object array in Java [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 6 years ago.
I have an object List with the name of cars and in this list I have some vehicle object. all objects values are different to each other. In all object here is custom field with the name of unit and in unit is another field with the name of unitType ... which is "T20" , "VT11" or any other ..
I want to sort this cars List according to unitType like:
if cars(0).getUnit().getUnitType().equals("T20") sort all the value first then other "VT11" and then all other...
How can I do this?? Is any suitable method in java?
my Unit class:
package com.vehicletracking.vtss.classes.bean;
import java.io.*;
public class Unit implements Serializable{
private int code;
private int unitId;
private String unitType; //X8, X1, X1+, VT10, VT200, SPT100
private Sim sim;
private String commType; //CSD, SMS, GPRS, AUTO
private int modemCode;
private long IMEI;
private String serialNo;
private InputReportProfile inputReportProfile;
private String firmware;
private String packageName;
private String password;
public Unit() {
}
public Unit(int unitId) {
this.unitId = unitId;
}
public Unit(int unitId, String unitType) {
this.unitId = unitId;
this.unitType = unitType;
}
public Unit(int unitId, String unitType, Sim sim) {
this.unitId = unitId;
this.unitType = unitType;
this.sim = sim;
}
public void setUnitId(int unitId) {
this.unitId = unitId;
}
public int getUnitId() {
return this.unitId;
}
public void setUnitType(String unitType) {
this.unitType = unitType;
}
public String getUnitType() {
return this.unitType;
}
public void setSim(Sim sim) {
this.sim = sim;
}
public void setCommType(String commType) {
this.commType = commType;
}
public void setModemCode(int modemCode) {
this.modemCode = modemCode;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public void setCode(int code) {
this.code = code;
}
public void setInputReportProfile(InputReportProfile inputReportProfile) {
this.inputReportProfile = inputReportProfile;
}
public void setPassword(String password) {
this.password = password;
}
public void setIMEI(long IMEI) {
this.IMEI = IMEI;
}
public Sim getSim() {
return this.sim;
}
public String getCommType() {
return commType;
}
public int getModemCode() {
return modemCode;
}
public String getSerialNo() {
return serialNo;
}
public int getCode() {
return code;
}
public InputReportProfile getInputReportProfile() {
return inputReportProfile;
}
public String getPassword() {
return password;
}
public long getIMEI() {
return IMEI;
}
public int hashCode() {
return unitId;
}
public boolean equals(Object obj) {
if (obj instanceof Unit) {
return this.unitId == ((Unit) obj).getUnitId();
}
return false;
}
public String toString() {
return this.unitId + "/" + this.unitType;
}
public String getFirmware() {
return firmware;
}
public void setFirmware(String firmware) {
this.firmware= firmware;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}
Car List:
List cars;
From Java 8 Documentation for Comparable:
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
According to above, you just have to implement Comparable, and provide an implementation for compareTo for your object. Collections.sort takes care of the rest.

Categories

Resources