Compare one ArrayList and combine common elements - java

I've been working on an algorithm to loop through one ArrayList containing a custom object. I'm now on hour 20 and I've gotten almost nowhere.
ArrayList<TicketItem> all = new ArrayList<>();
// ... 'all' gets filled here ... //
ArrayList<TicketItem> allCopy = new ArrayList<>(all);
for (int i = allCopy.size() - 1; i > 0; i--) {
TicketItem last = allCopy.get(i);
for (int j = 0; j < all.size(); j++) {
TicketItem compare = all.get(j);
if (last.getInt(TicketItem.TICKET_ITEM_ID) != compare.getInt(TicketItem.TICKET_ITEM_ID)) {
if (last.canBeGrouped(compare)) {
last.put(TicketItem.TICKET_ITEM_NUMBER, compare.getInteger(TicketItem.TICKET_ITEM_NUMBER));
allCopy.set(i, last);
break;
}
}
}
}
This works when it wants to and to be honest, it's probably really ugly. I just can't get my head around a better option.
The important method inside TicketItem is this one:
public boolean canBeGrouped(TicketItem other) {
if (other == null)
return false;
if (getBoolean(TicketItem.TICKET_ITEM_VOID))
return false;
if (other.getBoolean(TicketItem.TICKET_ITEM_VOID))
return false;
if (getInteger(TicketItem.MENU_ITEM) == null)
return false;
if (getInteger(TicketItem.MENU_ITEM).equals(other.getInteger(TicketItem.MENU_ITEM))
&& getBigDecimal(TicketItem.TICKET_ITEM_TOTAL).compareTo(
other.getBigDecimal(TicketItem.TICKET_ITEM_TOTAL)) == 0) {
ArrayList<TicketItemModifier> mThis = getModifiers();
ArrayList<TicketItemModifier> mOther = other.getModifiers();
if (mThis == null && mOther == null)
return true;
if (mThis != null && mOther != null) {
if (mThis.size() == mOther.size()) {
for (int i = 0; i < mThis.size(); i++) {
TicketItemModifier m1 = mThis.get(i);
TicketItemModifier m2 = mOther.get(i);
Integer m1MenuModifierId = m1.getInteger(TicketItemModifier.MENU_MODIFIER_ID);
Integer m2MenuModifierId = m2.getInteger(TicketItemModifier.MENU_MODIFIER_ID);
if (!(m1MenuModifierId != null && m2MenuModifierId != null && m1MenuModifierId
.equals(m2MenuModifierId))) {
return false;
}
}
return true;
}
}
}
return false;
}
Again, super ugly especially the for loop in there that works when it wants to. If need be I can modify hashCode and equals methods for both classes TicketItem and TicketItemModifier, however I would like to stay away from those two methods and do something along the lines of Comparable classes because just because they can be grouped does not mean they are equal.
What I want to do basically is go through one ArrayList filled with TicketItem objects and when two can be grouped I need to change the TicketItem object to match it.

I would suggest you create a new property or function like TickeItemCode which should be string concatenation of MENU_ITEM+ "-"+ TICKET_ITEM_TOTAL+ "-" + MENU_MODIFIER_IDs in modifiers list. you can filter the list to remove items where TICKET_ITEM_VOID is true and then sort by new property TickeItemCode and do grouping. This way you can reduce your time from n^2 to nlogn

Related

How can I check if two lists are equals?

I have to solve one problem, I don't know the reason why my code doesn't work.
I have to check if two lists I created are completely equals so they have the same value at the same position.
I'm allowed to use loops as well, even by I prefer the recursive mode.
Thank you so much for your help and time!
public static boolean checkEquality(Node n, Node m) {
if(n != null && m != null) {
boolean res = false;
while(n!=null) {
if(n.getElem()==m.getElem()) {
n = n.getNext();
m = m.getNext();
res = true;
}
else
{
res = false;
}
}
return res;
}
else
{
System.out.println("Lists empty!");
return true;
}
}
There are a couple of weak spots, so I give the solid solution:
public static boolean checkEquality(Node n, Node m) {
while (n != null && m != null) {
//if (!Objects.equals(n.getElem(), m.getElem())) {
if (n.getElem() != m.getElem()) {
return false;
}
n = n.getNext();
m = m.getNext();
}
return n == null && m == null;
}
Comparing can only be done while both n and m are not null. Your code only checks n.
== is not valid for instance for String. Instead of .equals one might also use Objects.equals which also tests for null.
getNext in every loop step.
two empty lists are also equal. Both lists should end at the same time.
The tst fails as soon as two compared nodes are not equal. So one should start with assuming a true result. And as soon as the comparison fails, one should no longer loop and certainly not overwrite res from false to true.
it would help if you elaborate what type of list u are comparing,
linkedlist or arrays. based on your function, it seems that you are planning to compare a linkedlist.
linkedlist documentation
arrays documentation
// sample comparison
boolean areIdentical(Node a_head, Node b_head) {
Node a = a_head, b = b_head;
while (a != null && b != null) {
if (a.data != b.data)
return false;
/* If we reach here, then a and b are not null
and their data is same, so move to next nodes
in both lists */
a = a.next;
b = b.next;
}
// If linked lists are identical, then 'a' and 'b'
// must be null at this point.
return (a == null && b == null);
}

How to simplify logic checking if all cells in a record of array are null using for

Can this code to be simplifed using for?
if ((col[0] == null) && (col[1] == null) && (col[2] == null) && (col[3] == null) && (col[4] == null)){
//statement
}
You can use a Java 8 feature with Stream API:
boolean allNull = Arrays.stream(col).allMatch(Objects::isNull);
Use a boolean flag:
boolean areAllNull = true;
for (int i = 0; i < col.length; i ++) {
if (col[i] != null) {
areAllNull = false;
break;
}
}
if (areAllNull) {
//statement
}
If you want to limit only to certain positions in the array change col.length by a variable or constant marking the limit:
int numberOfPositions = 5;
for (int i = 0; i < numberOfPositions ; i ++)`
To check if X elements in an array are null, you cannot reduce the number of checks (X) unless you can short-circuit them. However, you can have a cleaner "if" statement if you package it in a method:
if (isAllNull(col, 0, 4)){
// do stuff
}
public boolean isAllNull(Object[] col, int start, int end){
for (int index=start;index<=end;index++){
if (col[index] !=null){
return false;
}
}
return true;
}
This will return false immediately when it finds one of the values not null.

Recursion: Finding number of elements

I have following recursive method that returns the number of element in a nested Collection. A Collection contains child Collections plus Elements.
Is there a faster algorithm to achieve this?
int elementCount = 0;
#Override
public int getElementCount(CollectionDTO collectionDTO){
if(collectionDTO == null){
return elementCount;
}
if (collectionDTO.getChildCollectionDTOs() != null
&& collectionDTO.getChildCollectionDTOs().size() > 0) {
for (CollectionDTO collection : collectionDTO.getChildCollectionDTOs())
getElementCount(collection);
}
if(collectionDTO.elements != null && collectionDTO.elements.size() > 0)
elementCount +=collectionDTO.elements.size();
return elementCount;
}
In the worst case you are calling collectionDTO.getChildCollectionDTOs() three times so you should consider to call it just once, store the result in a variable and reuse it.
If another caller of this method which has the same reference to this object comes into play the usage of that class level variable elementCount will have side effects and won't return the correct result.
You should always use braces {} although they are optional for single lined if statements or for loops. This will just make your code less error prone.
Applying these points will lead to
#Override
public int getElementCount(CollectionDTO collectionDTO){
if(collectionDTO == null){
return 0;
}
int elementCount = 0;
if(collectionDTO.elements != null && collectionDTO.elements.size() > 0) {
elementCount +=collectionDTO.elements.size();
}
List<CollectionDTO> children = collectionDTO.getChildCollectionDTOs();
if (children == null){
return elementCount;
}
for (CollectionDTO collection : children)
elementCount += getElementCount(collection);
}
return elementCount;
}

Check if all values in a map are equal

I need to check if all values in a map are equal. I have a method to perform this task but would like to use a library or native methods. Limitations: Java 5 + Apache Commons libraries.
public static boolean isUnique(Map<Dboid,?> aMap){
boolean isUnique = true;
Object currValue = null;
int iteration = 0;
Iterator<?> it = aMap.entrySet().iterator();
while(it.hasNext() && isUnique){
iteration++;
Object value = it.next();
if(iteration > 1){
if (value != null && currValue == null ||
value == null && currValue != null ||
value != null && currValue != null & !value.equals(currValue)) {
isUnique = false;
}
}
currValue = value;
}
return isUnique;
}
What about this something like this:
Set<String> values = new HashSet<String>(aMap.values());
boolean isUnique = values.size() == 1;
how about
return (new HashSet(aMap.values()).size() == 1)
I know the original questions asks for solutions in Java 5, but in case someone else searching for an answer to this question is not limited to Java 5 here is a Java 8 approach.
return aMap.values().stream().distinct().limit(2).count() < 2
You could store the values in a Bidirectional Map and always have this property.
public static boolean isUnique(Map<Dboid,?> aMap) {
Set<Object> values = new HashSet<Object>();
for (Map.Entry<Dboid,?> entry : aMap.entrySet()) {
if (!values.isEmpty() && values.add(entry.getValue())) {
return false;
}
}
return true;
}
This solution has the advantage to offer a memory-saving short cut if there are many differences in the map. For the special case of an empty Map you might choose false as return value, change it appropriately for your purpose.
Or even better without a Set (if your Map does not contain null-values):
public static boolean isUnique(Map<Dboid,?> aMap) {
Object value = null;
for (Object entry : aMap.values()) {
if (value == null) {
value = entry;
} else if (!value.equals(entry)) {
return false;
}
}
return true;
}
As my comment above:
//think in a more proper name isAllValuesAreUnique for example
public static boolean isUnique(Map<Dboid,?> aMap){
if(aMap == null)
return true; // or throw IlegalArgumentException()
Collection<?> c = aMap.getValues();
return new HashSet<>(c).size() <= 1;
}

Methods that return boolean values

Okay, so my question is regarding boolean returns. For my Comp Sci homework, I have to make a course registration program using methods, and one of them is an add course method. Basically, you search for the class in a catalog, and if it matches you add it to the students schedule and return a boolean value of true. I did this, but for some reason it is giving me an error. Here is the code:
public static boolean addCourse(
Course[] catalog,
Course[] mySchedule,
int myNumCourses,
int dept,
int courseNum)
{
int j;
int i;
int k;
int deptCat;
int courseNumCat;
Course courseAdd = null;
char checkDay;
int checkTime;
if (mySchedule.length == myNumCourses) {
return false;
}
for (i = 0 ; i < catalog.length ; i++) {
Course course = catalog[i];
deptCat = course.getDepartment();
courseNumCat = course.getCourseNumber();
if (deptCat == dept && courseNumCat == courseNum) {
courseAdd = catalog[i];
break;
}
else continue; }
for (j = 0 ; j < myNumCourses ; j++) {
if (mySchedule[j] == null) {
mySchedule[j] = courseAdd;
return true;
}
else continue;
}
for (k = 0 ; k < mySchedule.length ; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay() && checkTime == courseAdd.getPeriod()) {
return false;
}
}
else continue;
}
}
Why doesn't it recognize the boolean return values? Is it because I placed them inside a loop?
You need to place a return-statement at the end of your method, even if you might know it will never be reached (the compiler is not smart enough to know that, which explains the error).
For instance, even this will not compile:
public static boolean foo() {
if (true)
return true;
}
unless we add a final return statement. What you have is analogous.
There is nothing wrong with putting your return values in loops, however, the compiler sees no guarantee that this method will return a value and thus raises an error. At the very end of the method you need to return either true or false, whichever is most appropriate. All of your returns are within conditionals and therefor could fail to execute leaving your function with no return statement.
You must explicitly return a boolean(true/false) in ALL code path.Because your function's return type is "boolean".
In your case,you must add a return statement after the last loop.
If you don't want to write to many "return xx" statement,you can change the return type of this function to "void".And throw Exception in the false cases.
I think there is a problem with the last loop. If the condition for returning false is never met, it continues until it get to the end of the schedule, without returning anything. If you were to add a return at the end of the method this loop could fall through to it. Did you mean to return true after the loop, if no 'return false' is executed?
for (k = 0; k < mySchedule.length; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay()
&& checkTime == courseAdd.getPeriod()) {
return false;
}
} else
continue;
}
Where ever you are using if statement its possible else also must return or flow must go to another return.ELSE is missing with return.

Categories

Resources