How to sort object array in Java [duplicate] - java

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.

Related

Sorting nested list of VO with Comparator

I am trying to sort a nested VO with comparator. I am able to do it with collection sort, but intellij shows a warning we must use comparators. But I could not figure this usage when we have list of object with nest objects.
Reports Comparators defined as lambda expressions which could be expressed using methods like Comparator.comparing(). Some comparators
like (person1, person2) ->
person1.getName().compareTo(person2.getName()) could be simplified
like this: Comparator.comparing(Person::getName). Also suggests to
replace chain comparisons with Comparator.thenComparing(), e.g. int
res = o1.first.compareTo(o2.first); if(res == 0) res =
o1.second.compareTo(o2.second); if(res == 0) res = o1.third -
o2.third; return res; will be replaced with
objs.sort(Comparator.comparing((Obj o) -> o.first).thenComparing(o ->
o.second).thenComparingInt(o -> o.third));
Here is my class
public class SortBaseVO {
public SortBaseVO(String prop1, String prop2, String prop3, String prop4, String sortBaseVO2) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
this.prop4 = prop4;
this.sortBaseVO2 = sortBaseVO2;
}
private String prop1;
private String prop2;
private String prop3;
private String prop4;
private String sortBaseVO2;
public String getSortBaseVO2() {
return sortBaseVO2;
}
public void setSortBaseVO2(String sortBaseVO2) {
this.sortBaseVO2 = sortBaseVO2;
}
public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public String getProp2() {
return prop2;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
public String getProp3() {
return prop3;
}
public void setProp3(String prop3) {
this.prop3 = prop3;
}
public String getProp4() {
return prop4;
}
public void setProp4(String prop4) {
this.prop4 = prop4;
}
}
Class B
public class SortBaseVO2 {
private String a;
private String b;
private String c;
private String d;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public String getD() {
return d;
}
public void setD(String d) {
this.d = d;
}
}
Current sorting done is sortBaseVOList is a list of sortBaseVO
Collections.sort(sortBaseVOList , (sortBaseVO1, sortBaseVO2) ->
sortBaseVO1.getsortBaseVO2().getB().concat(sortBaseVO1.getsortBaseVO2().getD())
.compareTo(sortBaseVO2.getsortBaseVO2().getB().concat(sortBaseVO2.getsortBaseVO2().getD()));
Can I change this to use Comparator?
I simulated your problem.
I suggest the following alternative as the right way to fix this warning:
List<SortBaseVO> sortBaseVOList = new ArrayList<>();
Collections.sort(sortBaseVOList , Comparator.comparing(SortBaseVO::getConcat));
where in your SortBaseVO class you must to define the following method:
public class SortBaseVO {
// all other methods
public String getConcat() {
return getSortBaseVO2().getB().concat(getSortBaseVO2().getD());
}
}

Parse Json with Gson in EnumClass

I have like this json.I'm using Gson to parse it and convert it in my custom class object.Here is a my java classes
public class ResponseModel {
private int resultCode;
private Match match;
public Match getMatch() {
return match;
}
public int getResultCode() {
return resultCode;
}
}
public class Match {
private Team team1;
private Team team2;
private double matchTime;
public Team getTeam1() {
return team1;
}
public Team getTeam2() {
return team2;
}
private Long matchDate;
private String stadiumAdress;
public double getMatchTime() {
return matchTime;
}
public Long getMatchDate() {
return matchDate;
}
public String getStadiumAdress() {
return stadiumAdress;
}
}
public class Team {
private String teamName;
private String teamImage;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamImage() {
return teamImage;
}
public void setTeamImage(String teamImage) {
this.teamImage = teamImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getBallPosition() {
return ballPosition;
}
public void setBallPosition(int ballPosition) {
this.ballPosition = ballPosition;
}
private int score;
private int ballPosition;
}
I'm using Gson like this
ResponseModel responseModel = GsonUtil.fromJson(response.toString(), ResponseModel.class);
public class GsonUtil {
public static <T> T fromJson(String json, Class<T> c) {
return new Gson().fromJson(json, c);
}
public static String toJson(Object c) {
return new Gson().toJson(c);
}
}
Everything working perfect,I can convert my json to custom class.But I want to use enum class with team1 and team2. My goal is to convert like this enum class
MatchTeamType:
TEAM1 (1);
TEAM2 (2);
How I can rewrite my code with enum class?
Thanks

how to write junit test cases for Row Mapper class in spring

Hi This is my Row Mapper class.
public class UserRowMapper implements RowMapper<UserData> {
#Override
public UserData mapRow(ResultSet resultSet, int line) throws SQLException {
UserData userData = new UserData();
try
{
userData.setUserID(resultSet.getString("User_ID"));
userData.setUserName(resultSet.getString("User_Name"));
userData.setUserPassword(resultSet.getString("User_Password"));
userData.setUserRole(resultSet.getString("User_Role"));
userData.setUserStatus(resultSet.getString("User_Status"));
userData.setUserLogStatus(resultSet.getString("UserLog_Status"));
userData.setUserAccountName(resultSet.getString("User_AccountName"));
userData.setUserAccountID(resultSet.getString("User_AccountID"));
userData.setUserEmailID(resultSet.getString("User_EmailID"));
userData.setUserPasswordStatus(resultSet.getString("User_Password_ExpiryStatus"));
userData.setUserIDStatus(resultSet.getString("User_ID_Status"));
userData.setAcatTenantID(resultSet.getLong("acatTenant_ID"));
userData.setUserRoleCode(resultSet.getLong("User_Role_Code"));
userData.setUserSkillSetCode(resultSet.getLong("User_SkillSet_Code"));
userData.setUserAccountCode(resultSet.getLong("User_Account_Code"));
return userData;
}
catch (EmptyResultDataAccessException e)
{
return null;
}
}
}
and this is my Model class.
public class UserData {
private String userID;
private String userPassword;
private String userRole;
private String userStatus;
private String userLogStatus;
private String userName;
private String userAccountName;
private String userAccountID;
private String userIDStatus;
private String userPasswordStatus;
private String userEmailID;
private String userAdminID;
private String deactivationComment;
private String reqPageID;
private String userSessionID;
private String reqFunctionalityID;
private long userAccountCode;
private long userRoleCode;
private long userSkillSetCode;
private long acatTenantID;
public long getUserAccountCode() {
return userAccountCode;
}
public void setUserAccountCode(long userAccountCode) {
this.userAccountCode = userAccountCode;
}
public long getUserRoleCode() {
return userRoleCode;
}
public void setUserRoleCode(long userRoleCode) {
this.userRoleCode = userRoleCode;
}
public long getUserSkillSetCode() {
return userSkillSetCode;
}
public void setUserSkillSetCode(long userSkillSetCode) {
this.userSkillSetCode = userSkillSetCode;
}
public long getAcatTenantID() {
return acatTenantID;
}
public void setAcatTenantID(long acatTenantID) {
this.acatTenantID = acatTenantID;
}
public String getReqFunctionalityID() {
return reqFunctionalityID;
}
public void setReqFunctionalityID(String reqFunctionalityID) {
this.reqFunctionalityID = reqFunctionalityID;
}
public String getReqPageID() {
return reqPageID;
}
public void setReqPageID(String reqPageID) {
this.reqPageID = reqPageID;
}
public String getUserSessionID() {
return userSessionID;
}
public void setUserSessionID(String userSessionID) {
this.userSessionID = userSessionID;
}
public String getUserAdminID() {
return userAdminID;
}
public void setUserAdminID(String userAdminID) {
this.userAdminID = userAdminID;
}
public String getDeactivationComment() {
return deactivationComment;
}
public void setDeactivationComment(String deactivationComment) {
this.deactivationComment = deactivationComment;
}
public String getUserIDStatus() {
return userIDStatus;
}
public void setUserIDStatus(String userIDStatus) {
this.userIDStatus = userIDStatus;
}
public String getUserPasswordStatus() {
return userPasswordStatus;
}
public void setUserPasswordStatus(String userPasswordStatus) {
this.userPasswordStatus = userPasswordStatus;
}
public String getUserEmailID() {
return userEmailID;
}
public void setUserEmailID(String userEmailID) {
this.userEmailID = userEmailID;
}
public String getUserAccountID() {
return userAccountID;
}
public void setUserAccountID(String userAccountID) {
this.userAccountID = userAccountID;
}
public String getUserAccountName() {
return userAccountName;
}
public void setUserAccountName(String userAccountName) {
this.userAccountName = userAccountName;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getUserLogStatus() {
return userLogStatus;
}
public void setUserLogStatus(String userLogStatus) {
this.userLogStatus = userLogStatus;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
The above classes are my Row Mapper and Model class.i do not know how to write junit test class for Row Mapper class .please any one guide me how to write junit test for these classes.
Hi here is my Junit test code for above classes.
public class UserRowMapperTest {
UserRowMapper userRowMapper=null;
#Before
public void runBeforeEachTest(){
userRowMapper= new UserRowMapper();
}
#After
public void runAfterEachTest(){
userRowMapper=null;
}
#Test
public void testMapRow(){
userRowMapper.mapRow(resultSet, line);
}
}
From my point of view there is nothing to test here.
You should create unit tests only for the methods which have some business logic. I don't see the reason to test the methods which are using just getters and setters because in general they don't do anything.
However, if you want just to practice this is the advice what you could do for the unit test. First of all check some questions on how to write the unit tests because it feels like you don't understand what you need/want to achieve.
In general this is the sketch of what you want:
#Test
public void testMapRow(){
// SETUP SUT
UserRowMapper userRowMapper = new UserRowMapper()
// fill (prepare) in the Object that you want to pass to a method.
ResultSet resultSet = createResultSet();
// EXERCISE
UserData resultData = userRowMapper.mapRow(resultSet, line);
// VERIFY
Assert.assertEquals(expectedValue, resultData.getSomeValue())
}
p.s. By the way, there is no point in line parameter in this method because you don't use it.
And about the NullPointerException, please, have a look to quite popular question about it.

Random access a value from Java HashMap, when using a custom class object as key for HashMap?

I am using a custom class object as the key for a HashMap. In this class definition, I have overridden the equals() and hashCode() methods.
public class TimeTableDataModel {
Map <Course, List <Timings>> tm;
TimeTableDataModel() {
tm = new HashMap<>();
}
void addCourseItem(Course course) {
tm.put(course, new ArrayList<Timings>());
}
void addNewTimeTableItem(Course course, Timings newTiming) {
List <Timings> t;
if(!tm.containsKey(course)) {
addCourseItem(course);
}
t = tm.get(course);
t.add(newTiming);
tm.put(course, t);
}
public static final class Course {
private final String courseCode;
private final String courseName;
private final String section;
private final String group;
Course(String code, String courseName, String section, String group) {
this.courseCode = code;
this.courseName = courseName;
this.section = section;
this.group = group;
}
public String getCourseCode() { return courseCode; }
public String getCourseName() { return courseName; }
public String getSection() { return section; }
public String getGroup() { return group; }
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Course)) {
return false;
}
Course otherObj = (Course) obj;
return Objects.equals(courseCode,otherObj.courseCode)
&& Objects.equals(courseName, otherObj.courseName)
&& Objects.equals(section, otherObj.section)
&& Objects.equals(group, otherObj.group);
}
#Override
public int hashCode() {
return Objects.hash(courseCode, courseName, section, group);
}
}
public static class Timings {
String time;
String day;
String room;
Timings(String time, String day) {
setTime(time);
setDay(day);
}
public String getTime() { return time; }
public String getday() { return day; }
public void setTime(String time) { this.time = time; }
public void setDay(String day){this.day = day;}
}
}
In above code I have created Course class to be used as the key for the HashMap and using a List<Timings> for values. What I intend is to get a List of timings when a Course is passed to hm.get(course). So far I can get a keyset then sequentially get values for each course.
for(Course c : timetable.tm.keySet()) {
System.out.println(c.getCourseCode() + " " + c.getCourseName());
for(Timings t : timetable.tm.get(c)) {
System.out.println(t.time + " " +t.room + " "+ t.day);
}
};
Here's the code that populates the HashMap
static TimeTableDataModel timetable = new TimeTableDataModel();
Course course = new Course(courseCode,null,section,group);
Timings dt = new Timings(time, getDayOfWeek(i));
dt.room = roomNo;
timetable.addNewTimeTableItem(course, dt);
So to get the timings for a particular course I have to traverse the whole HashMap until the desired course Key is found. What I want is a way to distinguish between each course object contained in the HashMap Key, so I can get Timings for any random course without traversing the whole KeySet.
Thanks in advance. Please ask if somethings is unclear in code
Problem what I see here is
if(!tm.containsKey(course)){
addCourseItem(course);
}
and
if (this == obj) {
return true;
}
because you are comparing the object. Since both are same class objects equals will always return true and map concludes it as duplicate key.

Get Duplicates Objects from ArrayList

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

Categories

Resources