I have an entity named Elementfisa, which contains as values (id,Post,Sarcina). Now, Post(Int Id,String Nume,String Tip) and Sarcina(Int Id,String Desc) are also entities. I have a List of all the elements I added as Elementfisa, and I want to get in a separate list the frequency of every Sarcina that every Elementfisa contains. This is my code right now:
int nr=0;
List<Integer> frecv=new ArrayList<Integer>();
List<Sarcina> sarcini = new ArrayList<>();
List<Elementfisa> efuri=findEFAll();
for (Elementfisa i : efuri)
{
nr=0;
for (Sarcina s : sarcini)
if (s.equals(i.getSarcina()))
nr=1;
if (nr==0)
{
int freq = Collections.frequency(efuri, i.getSarcina());
sarcini.add(i.getSarcina());
frecv.add(freq);
}
}
(findEFAll() returns every element contained in a Hashmap from a repository)
But for some reason, while the sarcini list contains all the Sarcina from every Elementfisa, the frequency list will show 0 on every position. What should I change so every position should show the correct number of occurrences?
You're using Collections.frequency() on efuri, a List<Elementfisa>. But you're passing i.getSarcina() to it, a Sarcina object. A List of Elementfisa cannot possibly contain a Sarcina object, so you get zero. You may have passed the wrong list to the method.
Edit:
To look at all Sarcinas in efuri, you can do this using Java 8 streams:
efuri.stream().map(element -> element.getSarcina())
.collect(Collectors.toList()).contains(i.getSarcina())
Breakdown:
efuri.stream() //Turns this into a stream of Elementfisa
.map(element -> element.getSarcina()) //Turns this into a stream of Sarcina
.collect(Collectors.toList()) //Turn this into a list
.contains(i.getSarcina()) //Check if the list contains the Sarcina
Are you sure you do not need to override equals() of Elementisa? (and hashcode() too). The default Java equals() does not seem to get what you want because it would be checking the identity (not the value) of two Elementisa objects, while in your logic, two such objects with the same values may be considered as equivalent.
For more information on equals(), see
What issues should be considered when overriding equals and hashCode in Java?
Related
For the below code it outputs " 1 ". and second code outputs " 2 " I don't understand why this is happening. Is it because I am adding the same object? How should I achieve the desired output 2.
import java.util.*;
public class maptest {
public static void main(String[] args) {
Set<Integer[]> set = new HashSet<Integer[]>();
Integer[] t = new Integer[2];
t[0] = t[1] = 1;
set.add(t);
Integer[] t1 = new Integer[2];
t[0] = t[1] = 0;
set.add(t);
System.out.println(set.size());
}
}
Second Code:
import java.util.*;
public class maptest {
public static void main(String[] args) {
Set<Integer[]> set = new HashSet<Integer[]>();
Integer[] t = new Integer[2];
t[0] = t[1] = 1;
set.add(t);
Integer[] t1 = new Integer[2];
t1[0] = t1[1] = 1;
set.add(t1);
System.out.println(set.size());
}
}
The Set implementation probably calls t.hashCode() and since arrays don't override the Object.hashCode method, the same object will have the same hashcode. Changing the array's contents thus does not affect its hash code. To get an array's hash code correctly, you should call Arrays.hashCode.
You shouldn't really put mutable things inside sets anyways, so I would suggest you put immutable lists into sets instead. If you want to stick with arrays, just create a new array, like you did with t1, and put it into the set.
EDIT:
For code 2, t and t1 are two different arrays so their hash code are different. Again, since the hashCode method is not overridden in arrays. The array's contents don't effect the hash code, whether or not they are the same.
A Set contains only distinct element (it is its nature). The basic implementation, HashSet, use hashCode() to first find a bucket containing values then equals(Object) to look for a distinct value.
Arrays are simple: their hashCode() use the default, inherited from Object, and therefore depending on reference. The equals(Object) is also the same than Object: it check only the identify, that is: references must be equals.
Defined as Java:
public boolean equals(Object other) {
return other == this;
}
If you want to put distinct arrays, you'll have to either try your luck with TreeSet and a proper implementation of Comparator, either wrap you array or use a List or another Set:
Set<List<Integer[]>> set = new HashSet<>();
Integer[] t = new Integer[]{1, 1};
set.add(Arrays.asList(t));
Integer[] t1 = new Integer[]{1, 1};
set.add(Arrays.asList(t1));
System.out.println(set.size());
As for mutability of the object used in a Set or a Map key:
fields used by the boolean equals(Object) should not be muted because the muted object could be then equals to another. The Set would no longer contains distinct values.
fields used by the int hashCode() should not be muted for hash based collection (HashSet, HashMap) because as said above their operate by putting items in a bucket. If the hashCode() change, it is likely the place of the object in the bucket will also change: the Set would then contains twice the same reference.
fields used by the int compareTo(T) or Comparator::compare(T,T) should not be muted for the same reason than equals: the SortedSet would not know there was a change.
If the need arise, you would have to first remove item from the set, then mutate it, the re-add it.
You're adding the Object to a Set which
contains no duplicate elements.
You are only ever adding one Object to the Set. You only change the value of it's contents. To see what I mean try adding System.out.println(set.add(t));.
As the add() method:
Returns true if this set did not already contain the specified element
Also your t1 is completely irrelevant in your first code snippet as you never use it.
In your second code snippet it outputs two because you are adding two different Integer[] Objects to the Set
Try printing out the hashcode of the Objects to see how this works:
Integer[] t = new Integer[2];
t[0] = t[1] = 1;
//Before we change the values
System.out.println(t.hashCode());
Integer[] t1 = new Integer[2];
t1[0] = t1[1] = 1;
//After we change the values of t
System.out.println(t.hashCode());
//Hashcode of the second object
System.out.println(t1.hashCode());
Output:
//Hashcode for t is the same before and after modifying data
366712642
366712642
//Hashcode for t1 is different from t; different object
1829164700
How java.util.Set implementations check for duplicate objects depends on the implementation, but per the documentation of Set, the appropriate meaning of "duplicate" is that o1.equals(o2).
Since HashSet in particular is based on a hash table, it will go about looking for a duplicate by computing the hashCode() of the object presented to it, and then going through all the objects, if any, in the corresponding hash bucket.
Arrays do not override hashCode() or equals(), so they implement instance identity, not value identity. Thus, regardless of the values of its elements, a given array always has the same hash code, and always equals() itself and only itself. You first code adds the same array object to a set two times. Regardless of the values of its elements, it is still the same set. The second code adds two different array objects to a set. Regardless of the values of their elements, they are different objects.
Note, too, that if you have mutable objects that implement value identity, such that their equality and hash codes depends on the values of their members, then modifying such an object while it is a member of a Set very likely breaks the Set. This is documented on a per-implementation basis.
Say I have Map<List<String>, List<String>> whatComesNext,
And while in a for loop, for every iteration I want to add the nth element of List<String> text to the value of whatComesNext. Why can I not perform whatComesNext.put(key, whatComesNext.get(key).add(text.get(n)))? The idea would be to retrieve the value from its respective key in the hashmap and add my desired String to it. This is assuming that every key in the hashmap has a value.
Below is my full code:
static void learnFromText(Map<List<String>, List<String>> whatComesNext, List<String> text) {
for (int i=0; i<=text.size()-3; i++) {
if (whatComesNext.containsKey(Arrays.asList(text.get(i),text.get(i+1)))==false) {
whatComesNext.put(Arrays.asList(text.get(i),text.get(i+1)), Arrays.asList(""));
}
whatComesNext.put(Arrays.asList(text.get(i),text.get(i+1)), whatComesNext.get(Arrays.asList(text.get(i),text.get(i+1))).add(text.get(i+2)));
}
}
The Arrays.asList() looks complicated, but it's because I was getting null maps when trying to intialize my own String Lists to try and hold my keys and values, which someone told me was because I was repeatedly clearing the lists that the keys & values were assigned to, leaving them null. I thought I'd solve that problem by referring directly to the original List<String> text, because that remains unchanged. The idea is to first check if a key is not present in the map, and if so assign it an empty List as a value, and then add a String from text to the value of the map.
The error I get when running the code is Error: incompatible types: boolean cannot be converted to java.util.List<java.lang.String> in the line whatComesNext.get(Arrays.asList(text.get(i),text.get(i+1))).add(text.get(i+2)));. I don't understand where this could go wrong, because I don't see which method is returning a boolean.
The error comes from the fact that List.add(Object o) returns a boolean and not the List itself. The Map is declared to contain instances of List<String> as value. If you simply want to add a value to a list, just retrieve it from the map and call add on it. Check the result of the get-process for null and create a new list and put it into the Map if that's the case
I can see a couple of other problems as well:
You call Arrays.asList(...) multiple times creating multiple lists with the same elements. This is a major performance issue and you're just lucky, that the returned list is actually implementing equals, so that your logic is actually working (I expected that to be the problem of your "doesn't work"-description before you updated it.
If the key doesn't exist, you're creating a List containing an empty text. If that should be an empty list, that's not what you're doing and you might run into problems later on, when you work with text-values (that is the empty text as first element) that weren't part of the original input values.
Without changing the type of the key of the Map a - in my eyes - better implementation would look like this:
static void learnFromText(Map<List<String> whatComesNext, List<String>, List<String> text) {
for (int i=0; i<= text.size() - 3; i++) {
List<String> listKey = text.subList(i, i+2);
List<String> value = whatComesNext.get(listKey);
if (value == null) {
value = new ArrayList<>();
whatComesNext.put(listKey, value);
}
value.add(text.get(i+2)));
}
}
The calculation of the list for the keys happens only once, increasing performance and reducing the need of resources. And I think it's more readable that way as well.
The .add() method returns a boolean, your parenthesis are misplaced, replace your last line with this one:
whatComesNext.put(Arrays.asList(text.get(i),text.get(i+1)), whatComesNext.get(Arrays.asList(text.get(i),text.get(i+1)))).add(text.get(i+2));
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).
I want to achieve the following, I have a collection of dates in a list form which I want deduped and sorted. I'm using collections.sort to sort the list in ascending date order and then using a treeSet to copy and dedupe elements from the list. This is a 2 shot approach ? Is there a faster, 1 step approach ?
EDIT::
Metadata
{
String name;
Date sourceDate;
}
Basically I want to order Metadata object based on the sourceDate and dedupe it too.
You can skip the Collections#sort step: TreeSet will remove duplicates and sort the entries. So basically it is a one line operation:
Set<Date> sortedWithoutDupes = new TreeSet<Date> (yourList);
If the Date is a field in your object, you can either:
have your object implement Comparable and compare objects based on their date
or pass a Comparator<YourObject> as an argument to the TreeSet constructor, that sorts your objects by date
In both cases, you don't need to pre-sort your list.
IMPORTANT NOTE:
TreeSet uses compareTo to compare keys. So if 2 keys have the same date but different names, you should make sure that your compare or compareTo method returns a non-0 value, otherwise the 2 objects will be considered equal and only one will be inserted.
EDIT
The code could look like this (not tested + you should handle nulls):
Comparator<Metadata> comparator = new Comparator<Metadata>() {
#Override
public int compare(Metadata o1, Metadata o2) {
if (o1.sourceDate.equals(o2.sourceDate)) {
return o1.name.compareTo(o2.name);
} else {
return o1.sourceDate.compareTo(o2.sourceDate);
}
}
};
Set<Metadata> sortedWithoutDupes = new TreeSet<Metadata> (comparator);
sortedWithoutDupes.addAll(yourList);
TreeSet will automatically sort its elements, so you shouldn't need to sort the list before adding to the set.
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.