Wish to compare, two (object) lists for
Not null
Not empty
Equal Size
Nth Element Field values are same
Possible?
String A = "one,two,three|four,five,six|seven,eight,nine"
String B = "three,six,nine"
List L1 = List.of(A.split("\\|"));
List L2 = List.of(B.split(","));
Give object of List L1, if the third sub value of an element matches with element of the List L2.
Note: This answered the question when it was:
Wish to compare, two (object) lists for
1. Not null
2. Not empty
3. Equal Size
4. Nth Element Field values are same
Possible?
Since then, it was significantly changed...
Seems like you can go with Objects.equals(list1, list2);
When only one of the lists is null, it returns false.
2./3. When the sizes are different, it will return false.
When the elements differ, it will also return false.
In any other case, it will return true.
Disclaimer: This works for the standard Lists in the Collections Framework. There might be other implementations which implement equals() differently (and therefore behave differently when applied to Objects.equals()).
Related
Basically I would like to know how I can check two lists to see if the position of the elements are the same in both lists after sorting one with Collections package Collections.sort, e.g:
List<String> first = new ArrayList<String>();
a.add("one");
a.add("two");
List<String> second = new ArrayList<String>();
b.add("two");
b.add("one");
Collections.sort(second);
then check if one lists has the elements in the same order, returning a boolean false if the elements position is the same and true otherwise.
PS: I though of just checking the position of the last element but im not sure if thats a good way of doing this.
Just use first.equals(second) after sorting one of the lists. If both have the same number of elements and the elements are pair-wise equal, you'll get true.
This relies, of course, on the element type of the Lists to override equals properly.
I have a function in java like
void remove(List<Var> vars, List<List<Value>> vals) {
int index = calculateIndex();
vars.removeAll(vars.subList(index, vars.size()));
vals.removeAll(vals.subList(index, vals.size()));
}
always both lists have the same number of elements before enter the method, but, after removeAll vars have one element more than vals, index is between zero and the size of the lists, why could this be happening?
If I understand correctly what you're trying to do, the code to remove the sublists should look like
int index = calculateIndex();
vars.subList(index, vars.size()).clear();
vals.subList(index, vals.size()).clear();
removeAll isn't the right tool for the job. The purpose of removeAll is to look at all the elements in collection A, and remove elements in collection B that are equal to any element in collection A. I believe it uses .equals to determine which elements are equal, not reference equality, which means that you could be removing some elements you don't intend to remove. Furthermore, since the collection A in this case would be a sublist of collection B, so that they overlap, I wouldn't count on removeAll to function correctly anyway, although it might; using overlapping lists in this situation could lead to havoc.
As an alternative design and not necessarily on track, I think it would be a nicer method if you actually constructed a new List containing the difference and returned it preserving both the original lists, otherwise its a slight code smell.
i.e.
List<Var> difference(List<Var> vars, List<List<Value>> vals) {
List<Var> results = new ArrayList<Var>();
// Loop through Vars and Vals appropriately adding Var to results based on some criteria
// ....
return results;
}
This way you preserve List vars from appearing to magically change when passed in as a input parameter to a method.
I have an ArrayList<SomeObject> in java which contains some <SomeObject> multiple times.
I also have a Set<SomeObject>, which contains some elements one time only. The elements are only uniquely distinguishable only by their name (String SomeObject.Name).
How am I possible to see if the list has exactly the same elements as the set, but maybe multiple times?
Thanks
There are several collections libraries to do this. For example commons-collection: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isEqualCollection-java.util.Collection-java.util.Collection-
eg. CollectionUtils.isEqualCollection(myList, mySet)
If you have to write it yourself, no libraries, then just check that each contains all the elements of the other:
`mySet.containsAll(myList) && myList.containsAll(mySet)`
It seems like the simplest one-line solution to this is probably
return new HashSet<SomeObject>(list).equals(set);
...which just identifies the unique elements of list and verifies that that matches set exactly.
You could convert the ArrayList to a set by using HashSet:
HashSet listSet = new HashSet(arrayList);
To check whether the ArrayList initially has more elements, just compare the listSet and arrayList size() results:
boolean sameSize = listSet.size() == arrayList.size()
Then you can get the intersection of the two sets (the elements they have in common):
listSet.retainAll(set1)
If listSet.size() == set1.size() now, then they had the same elements, as all elements in the two lists were shared in common. To check whether the arrayList had repeating elements initially, check the value of the boolean from before: if sameSize is true, then they did, false means that they didn't.
You have a couple of options:
add all you List elements to Set and check if the size is the same;
create a new List based on your Set and check is they are equals.
All Java collections have method boolean containsAll(collection<>), so if we want to check if two collections contain same elements, we can write collection1.containsAll(collection2) && collection2.containsAll(collection1) which will return true if collection1 and collection2 contain same elements.
Create a Hash that is a String and an Integer of the count of how many time. Interate thought the list create a Hash entry and setting to one if element exists already add one to the count.
Hash<String, Integer> hash = new HashMap<String, Integer>();
for (String s : list) {
if (hash.containsKey(s))
hash.put(s, hash.get(s)++);
else
hash.put(s,1);
}
I have a Map of the form Map<String,List<String>>. The key is a document number, the List a list of terms that match some criteria and were found in the document.
In order to detect duplicate documents I would like to know if any two of the List<String> have exactly the same elements (this includes duplicate values).
The List<String> is sorted so I can loop over the map and first check List.size(). For any two lists
that are same size I would then have to compare the two lists with List.equals().
The Map and associated lists will never be very large, so even though this brute force approach will not scale well it
will suffice. But I was wondering if there is a better way. A way that does not involve so much
explicit looping and a way that will not produce an combinatorial explosion if the Map and/or Lists get a lot larger.
In the end all I need is a yes/no answer to the question: are any of the lists identical?
You can add the lists to a set data structure one by one. Happily the add method will tell you if an equal list is already present in the set:
HashSet<List<String>> set = new HashSet<List<String>>();
for (List<String> list : yourMap.values()) {
if (!set.add(list)) {
System.out.println("Found a duplicate!");
break;
}
}
This algorithm will find if there is a duplicate list in O(N) time, where N is the total number of characters in the lists of strings. This is quite a bit better than comparing every pair of lists, as for n lists there are n(n-1)/2 pairs to compare.
Use Map.containsValue(). Won't be more efficient than what you describe, but code will be cleaner. Link -> http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsValue%28java.lang.Object%29
Also, depending on WHY exactly you're doing this, might be worth looking into this interface -> http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/BiMap.html
Not sure if it's a better way, but a cleaner way would be to create an object that implements Comparable and which holds one of your List. You could implement hashcode() and equals() as you describe above and change your map to contain instances of this class instead of the Lists directly.
You could then use HashSet to efficiently discover which lists are equal. Or you can add the values collection of the map to the HashSet and compare the size of the hashset to the size of the Map.
From the JavaDoc of 'List.equals(Object o)':
Compares the specified object with this list for equality. Returns
true if and only if the specified object is also a list, both lists
have the same size, and all corresponding pairs of elements in the two
lists are equal. (Two elements e1 and e2 are equal if (e1==null ?
e2==null : e1.equals(e2)).) In other words, two lists are defined to
be equal if they contain the same elements in the same order. This
definition ensures that the equals method works properly across
different implementations of the List interface.
This leads me to believe that it is doing the same thing you are proposing: Check to make sure both sides are a List, then compare the sizes, then check each pair. I wouldn't re-invent the wheel there.
You could use hashCode() instead, but the JavaDoc there seems to indicate it's looping as well:
Returns the hash code value for this list. The hash code of a list is
defined to be the result of the following calculation:
int hashCode = 1;
Iterator<E> i = list.iterator();
while (i.hasNext()) {
E obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
So, I don't think you are saving any time. You could, however, write a custom List that calculates the hash as items are put in. Then you negate the cost of doing looping.
I have two lists with different objects in them.
List<Object1> list1;
List<Object2> list2;
I want to check if element from list1 exists in list2, based on specific attribute (Object1 and Object2 have (among others), one mutual attribute (with type Long), named attributeSame).
right now, I do it like this:
boolean found = false;
for(Object1 object1 : list1){
for(Object2 object2: list2){
if(object1.getAttributeSame() == object2.getAttributeSame()){
found = true;
//also do something
}
}
if(!found){
//do something
}
found = false;
}
But I think there is a better and faster way to do this :)
Can someone propose it?
Thanks!
If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line
!Collections.disjoint(list1, list2);
If you need to test a specific property, that's harder. I would recommend, by default,
list1.stream()
.map(Object1::getProperty)
.anyMatch(
list2.stream()
.map(Object2::getProperty)
.collect(toSet())
::contains)
...which collects the distinct values in list2 and tests each value in list1 for presence.
To shorten Narendra's logic, you can use this:
boolean var = lis1.stream().anyMatch(element -> list2.contains(element));
You can use Apache Commons CollectionUtils:
if(CollectionUtils.containsAny(list1,list2)) {
// do whatever you want
} else {
// do other thing
}
This assumes that you have properly overloaded the equals functionality for your custom objects.
There is one method of Collection named retainAll but having some side effects for you reference
Retains only the elements in this list that are contained in the
specified collection (optional operation). In other words, removes
from this list all of its elements that are not contained in the
specified collection.
true if this list changed as a result of the call
Its like
boolean b = list1.retainAll(list2);
Loius answer is correct, I just want to add an example:
listOne.add("A");
listOne.add("B");
listOne.add("C");
listTwo.add("D");
listTwo.add("E");
listTwo.add("F");
boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true
faster way will require additional space .
For example:
put all items in one list into a HashSet ( you have to implement the hash function by yourself to use object.getAttributeSame() )
Go through the other list and check if any item is in the HashSet.
In this way each object is visited at most once. and HashSet is fast enough to check or insert any object in O(1).
According to the JavaDoc for the .contains(Object obj):
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one
element e such that (o==null ? e==null : o.equals(e)).
So if you override your .equals() method for your given object, you should be able to do: if(list1.contains(object2))...
If the elements will be unique (ie. have different attributes) you could override the .equals() and .hashcode() and store everything in HashSets. This will allow you to check if one contains another element in constant time.
to make it faster, you can add a break; that way the loop will stop if found is set to true:
boolean found = false;
for(Object1 object1 : list1){
for(Object2 object2: list2){
if(object1.getAttributeSame() == object2.getAttributeSame()){
found = true;
//also do something
break;
}
}
if(!found){
//do something
}
found = false;
}
If you would have maps in stead of lists with as keys the attributeSame, you could check faster for a value in one map if there is a corresponding value in the second map or not.
Can you define the type of data you hold ? is it big data ? is it sorted ?
I think that you need to consider different efficiency approaches depending on the data.
For example, if your data is big and unsorted you could try and iterate the two lists together by index and store each list attribute in another list helper.
then you could cross check by the current attributes in the helper lists.
good luck
edited : and I wouldn't recommend overloading equals. its dangerous and probably against your object oop meaning.
org.springframework.util.CollectionUtils
boolean containsAny(java.util.Collection<?> source, java.util.Collection<?> candidates)
Return true if any element in 'candidates' is contained in 'source'; otherwise returns false
With java 8, we can do like below to check if one list contains any element of other list
boolean var = lis1.stream().filter(element -> list2.contains(element)).findFirst().isPresent();