Handle differences between two arraylists - java

My question is that I am going to compare two arraylists in Java
e.g
String prop1 = "String"
String prop2 = "OtherString"
MyObject obj1 = new MyObject(prop1,prop2);
MyObject obj2 = new MyObject(prop1,prop2);
MyObject obj3= new MyObject(prop1,prop2);
ArrayList<MyObject> array1 = new Arraylist<>();
ArrayList<MyObject> array2 = new Arraylist<>();
//array 1 has 3 objects
array1.add(obj1);array1.add(obj2);array1.add(obj3);
//array 2 has 2 objects
array2.add(obj1);array2.add(obj2);
With a comparison method i know these arrays are different
(My method returns false if the arrays have the same elements even if they are not in the same order, and true if they have the same elements)
So, the method is going to return FALSE
My question is:
if(!methodToCompareArrays(array1,array2)){
//HOW TO GET THE DIFFERENT objects (IN THIS CASE, obj3 is the different object)
//this is the question :)
}else{
//If there is no difference, well, it doesn't matter too much
Notice that I'm going to have multiple objects into these arraylists, and also the method efficiency is important (not crucial, but important at least). I've seen the answers here But I'm not sure which one would be better or worst
Thanks in advance.

You should probably use java's set interfaces for this.
Now, one thing that's going to be important is having a good equals method on MyObject to be able to compare whether two MyObjects are the same.
Then you could use that documentation link above to check the intersection of two sets. If the items that are in both sets are the same number of items as in one set, then they're the same set (irrespective of order).
HashSet<MyObject> set1 = new HashSet<MyObject>(array1);
HashSet<MyObject> set2 = new HashSet<MyObject>(array2);
Set<MyObject> intersection = new HashSet<MyObject>(set1);
intersection.retainAll(set2);
if(intersection.size() == set2.size()) {
// They're the same.
} else {
HashSet<MyObject> itemsOnlyInSet1 = intersection;
HashSet<MyObject> itemsOnlyInSet2 = set2.retainAll(set1);
}

If the objects in these lists aren't important for you, you can do something like:
array1.removeAll(array2);
This will remove from array1, all the elements that exist in array2.
So if array1 = [obj1, obj2, obj3] and
array2 = [obj1, obj2]
After the removeAll:
array1 = [obj3] and
array2 = [obj1, obj2]
If you cannot remove the objects from either list then make a temp List and remove from there to get extra object.

I am not sure I understand what your question is but if you are trying to compare and sort list of objects, the best option is to look up TreeMaps from the Collections API. Try this:
Difference between HashMap, LinkedHashMap and TreeMap

Related

How to count unique values ​in a map that are complex objects

I have the following sample structure:
class MyObject {
private String type;
private String level;
}
Map<String,List<MyObject>> map = new HashMap<>();
MyObject myObject1 = new MyObject();
myObject1.setType("x");
myObject1.setLevel("5");
MyObject myObject2 = new MyObject();
myObject2.setType("y");
myObject2.setLevel("5");
List<MyObject> list1 = new ArrayList<>();
list1.add(myObject1);
list1.add(myObject2);
map.put("1",list1);
MyObject myObject3 = new MyObject();
myObject3.setType("x");
myObject3.setLevel("4");
List<MyObject> list2 = new ArrayList<>();
list2.add(myObject3);
map.put("2",list2);
MyObject myObject4 = new MyObject();
myObject4.setType("x");
myObject4.setLevel("5");
MyObject myObject5 = new MyObject();
myObject5.setType("y");
myObject5.setLevel("5");
List<MyObject> list3 = new ArrayList<>();
list3.add(myObject4);
list3.add(myObject5);
map.put("3",list3);
...
Based on this map, I need to create an intermediate object or some structure where I will store information about the unique values ​​of the map. In the example above, key 1 and key 3 are the same value
so I need to store the information that the combination x = 5, y = 5 occurred twice in the map. The combination x = 4 appeared once in the map. There can be many combinations.
Any suggestions on how to do it the easiest way?
Since this looks like a homework question asking how to generally do the task I will not include code.
Think through what you have to do, write methods you'll need, implement them when you think you have all the pieces you need. Start with a stub for the method that does what you want.
The thing you can have duplicates of in the map (why are they in the map, no idea) are lists. Write a method that compares lists and returns whether they are the same.
To write that method you need a method that can compare MyObject. Best way would be to override equals() method.
Next, it'll be a question if order in the lists matters. If yes, than List equals method will work for you (read the javadoc to see exactly what it does). If not you'll need to write custom code to handle that, or sort the lists before comparison (which would involve writing a comparator for MyObject), or use a library that has that functionality (there should be something in Apache Commons).
Now that we have all that all we come back to the main method, use the ones we wrote appropriately, and all we need is do something with the results. Generally anything will do, a map with the list as key and amount of occurences as value will be simplest unless you have some more constraints or operations to do on the results.

Compare and match arrays with different sizes

I have a couple of arrays with different sizes; say, array A and array B.
Array A
[chery, chery, uindy, chery, chery]
Array B
[chery, uindy]
Need to check whether the values present in Array A is available in Array B or not. In the above example, all the values in Array A is available in Array B. Please help this out with the Java code. Thanks!
You can convert your arrays to a List and then use the containsAll method to see if a particular list contains all elements described in another list.
You would get better performance out of it if they were Sets instead.
Example:
List<String> firstList = Arrays.asList("chery", "chery", "unid", ...);
List<String> secondList = Arrays.asList("chery", "unid", ...);
System.out.println(secondList.containsAll(firstList));
If the performance of this method in particular is getting a bit dodgy, then consider converting the lists into Sets instead:
Set<String> firstSet = new HashSet<>(Arrays.asList("chery", "chery", "unid", ...));
In the example I am using integers but can be used for other types also with slight modifications.
First put a loop on array A elements.
for(int i =0; i<A.length(); i++)
{
//this loop will transverse with all elements in array A.
}
Now inside this for loop make another for loop which transverse through elements of loop B.
for(int i =0; i<A.length(); i++)
{
for(int j=0; j<B.length();j++)
{
if(A[i] == B[j])
{ System.out.println("this element is in array A and B"); }
}
}
Now if you want to check if all elements of A are in B you can make a boolean. this boolean is true as long each element in A is found at least once in B. as soon as you find one element which is not present on both arrays you can exit.
Base on your requirement, you are going to find out if B is a superset of A (I mean the distinct values).
This can be easily done by one line like this:
String[] aArr = {.....};
String[] bArr = {.....};
return new HashSet<String>(Arrays.asList(bArr)).containsAll(Arrays.asList(aArr));
In brief, make B a Set, and check if B set contains all values of A
so, if A = {Apple, Apple, Banana, Cherry} and B = {Apple, Banana, Cherry, Pineapple}, it will return true (that's the behavior base on your description)
For arrays of Strings :
for (String str : array1)
{
System.out.println(ArrayUtils.contains(array2, str);
}
An array is not a good data structure for doing this. A Set is better. So convert your two arrays to Set objects, then simply use Set.equals(). Either do the conversion by creating new objects just before the comparison, or use a Set everywhere.
Set<String> setA = new HashSet<>(Arrays.asList(new String[]{"chery", "chery", "uindy", "chery", "chery"}));
Set<String> setB = new HashSet<>(Arrays.asList(new String[]{"chery", "uindy"}));
System.out.println("Sets are equal: " +setA.equals(setB));
The equals method of AbstractSet says
Compares the specified object with this set for equality. Returns true
if the given object is also a set, the two sets have the same size,
and every member of the given set is contained in this set. This
ensures that the equals method works properly across different
implementations of the Set interface. This implementation first checks
if the specified object is this set; if so it returns true. Then, it
checks if the specified object is a set whose size is identical to the
size of this set; if not, it returns false. If so, it returns
containsAll((Collection) o).

Java removeAll() and Objects

I have two arrayLists that contain objects of my Class Report Object.
Report Object has couple of fields but most important are Tag(String) and Attr(String).
During the execution of the program two arrayLists are populated with that objects. These arrayLists represent old collection of the ReportObjects and the new one.
I want to know what objects were added to the new arrayList and what objects were removed from old ArrayList.
ReportObject obj1 = new ReportObject("Tag", "Attr", "XPath", "Parent", null);
ReportObject obj2 = new ReportObject("Tag2", "Attr", "XPath", "Parent", null);
ReportObject obj3 = new ReportObject("Tag", "Attr", "XPath", "Parent", null);
ArrayList<ReportObject> newList = new ArrayList<>();
ArrayList<ReportObject> oldList = new ArrayList<>();
ArrayList<ReportObject> added = new ArrayList<>();
ArrayList<ReportObject> removed = new ArrayList<>();
newList.add(obj1);
newList.add(obj2);
oldList.add(obj3);
added.addAll(newList);
added.removeAll(oldList);
Problem is I still have two elements in added ArrayList. That because obj1 and obj3 are different objects?
When I do two loops and iterate over them while checking if objects has same field values i still get same results.
So in added arrayList I should have only obj2 and in removed arrayList should be empty.
A String is an Object in Java. This will work. Java Collections make heavy use of equals to determine if an object is present in the collection. If you don't override equals, this will remove only objects that are present in both collections. That usually is the intended result though.
I guess you have an ID on the class you're making an object, then go like this:
for(ReportObject obj : xmlModel_New)
{
int i = 0;
for(ReportObject obj2 : xmlModel_Old){
if(obj.get(i).getId() != obj2.get(i).getId())
{
addedTags.add(obj);
}
i++;
}
}
Something like that.
You need to override the equals(Object obj) and hashCode() method in the ReportObject class. The default uses the memory location which I doubt is how you are trying to compare them. What makes them equal? One attribute or all the attributes? You have to define that. Your example would change to...
if(!obj.equals(obj2))
{
addedTags.add(obj);
}
I think this question is being downvoted probably because it has been answered before or maybe because it is kind of unclear what you are asking. Post more details and I will try to help.
Also, check out some of these links:
What issues should be considered when overriding equals and hashCode in Java?
How do I compare strings in Java?

Java - Casting, Generics, Objects and Arrays

I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.

Compare new Integer Objects in ArrayList Question

I am storing Integer objects representing an index of objects I want to track. Later in my code I want to check to see if a particular object's index corresponds to one of those Integers I stored earlier. I am doing this by creating an ArrayList and creating a new Integer from the index of a for loop:
ArrayList<Integer> courseselectItems = new ArrayList();
//Find the course elements that are within a courseselect element and add their indicies to the ArrayList
for(int i=0; i<numberElementsInNodeList; i++) {
if (nodeList.item(i).getParentNode().getNodeName().equals("courseselect")) {
courseselectItems.add(new Integer(i));
}
}
I then want to check later if the ArrayList contains a particular index:
//Cycle through the namedNodeMap array to find each of the course codes
for(int i=0; i<numberElementsInNodeList; i++) {
if(!courseselectItems.contains(new Integer(i))) {
//Do Stuff
}
}
My question is, when I create a new Integer by using new Integer(i) will I be able to compare integers using ArrayList.contains()? That is to say, when I create a new object using new Integer(i), will that be the same as the previously created Integer object if the int value used to create them are the same?
I hope I didn't make this too unclear. Thanks for the help!
Yes, you can use List.contains() as that uses equals() and an Integer supports that when comparing to other Integers.
Also, because of auto-boxing you can simply write:
List<Integer> list = new ArrayList<Integer>();
...
if (list.contains(37)) { // auto-boxed to Integer
...
}
It's worth mentioning that:
List list = new ArrayList();
list.add(new Integer(37));
if (list.contains(new Long(37)) {
...
}
will always return false because an Integer is not a Long. This trips up most people at some point.
Lastly, try and make your variables that are Java Collections of the interface type not the concrete type so:
List<Integer> courseselectItems = new ArrayList();
not
ArrayList<Integer> courseselectItems = new ArrayList();
My question is, when I create a new Integer by using new Integer(i) will I be able to compare integers using ArrayList.contains()? That is to say, when I create a new object using new Integer(i), will that be the same as the previously created Integer object if the int value used to create them are the same?
The short answer is yes.
The long answer is ...
That is to say, when I create a new object using new Integer(i), will that be the same as the previously created Integer object if the int value used to create them are the same?
I assume you mean "... will that be the same instance as ..."? The answer to that is no - calling new will always create a distinct instance separate from the previous instance, even if the constructor parameters are identical.
However, despite having separate identity, these two objects will have equivalent value, i.e. calling .equals() between them will return true.
Collection.contains()
It turns out that having separate instances of equivalent value (.equals() returns true) is okay. The .contains() method is in the Collection interface. The Javadoc description for .contains() says:
http://java.sun.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)
boolean contains(Object o)
Returns true if this collection
contains the specified element. More
formally, returns true if and only if
this collection contains at least one
element e such that (o==null ? e==null
: o.equals(e)).
Thus, it will do what you want.
Data Structure
You should also consider whether you have the right data structure.
Is the list solely about containment? is the order important? Do you care about duplicates? Since a list is order, using a list can imply that your code cares about ordering. Or that you need to maintain duplicates in the data structure.
However, if order is not important, if you don't want or won't have duplicates, and if you really only use this data structure to test whether contains a specific value, then you might want to consider whether you should be using a Set instead.
Short answer is yes, you should be able to do ArrayList.contains(new Integer(14)), for example, to see if 14 is in the list. The reason is that Integer overrides the equals method to compare itself correctly against other instances with the same value.
Yes it will, because List.contains() use the equals() method of the object to be compared. And Integer.equals() does compare the integer value.
As cletus and DJ mentioned, your approach will work.
I don't know the context of your code, but if you don't care about the particular indices, consider the following style also:
List<Node> courseSelectNodes = new ArrayList<Node>();
//Find the course elements that are within a courseselect element
//and add them to the ArrayList
for(Node node : numberElementsInNodeList) {
if (node.getParentNode().getNodeName().equals("courseselect")) {
courseSelectNodes.add(node);
}
}
// Do stuff with courseSelectNodes
for(Node node : courseSelectNodes) {
//Do Stuff
}
I'm putting my answer in the form of a (passing) test, as an example of how you might research this yourself. Not to discourage you from using SO - it's great - just to try to promote characterization tests.
import java.util.ArrayList;
import junit.framework.TestCase;
public class ContainsTest extends TestCase {
public void testContains() throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>();
assertFalse(list.contains(new Integer(17)));
list.add(new Integer(17));
assertTrue(list.contains(new Integer(17)));
}
}
Yes, automatic boxing occurs but this results in a performance penalty. Its not clear from your example why you would want to solve the problem in this manner.
Also, because of boxing, creating the Integer class by hand is superfluous.

Categories

Resources