0

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?

Artyomska
  • 973
  • 1
  • 16
  • 40

2 Answers2

1

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
Moira
  • 9,571
  • 3
  • 40
  • 61
0

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?

Community
  • 1
  • 1
leeyuiwah
  • 5,456
  • 4
  • 31
  • 54
  • The list itself contains `Elementisa`s but they are checking if the list contains `Sarcina`s, equals wouldn't help much here – Moira Jan 03 '17 at 18:40