-1
public static int amountKurse (List<Studie> lstd) {
    int result = (int) lstd.stream().map(Studie::getKurse).count();
    return result;
}

private Map<Kurs,Integer> kurse = new HashMap<>();

public Set<Kurs> getKurse(){
    return kurse.keySet();
}

I want to count the number of Kurse in all my Studie objects. My current result is 20, when it should be 132 I am guessing that my function is only counting the amount of Studie Would be grateful for some help on this.

0

2 Answers 2

5

If getKurse() returns a Set and you want to count the total number of elements of all these Sets, use:

int result = (int) lstd.stream().flatMap(s -> s.getKurse().stream()).count();

or, if you want to avoid counting duplicates:

int result = (int) lstd.stream().flatMap(s -> s.getKurse().stream()).distinct().count();
Sign up to request clarification or add additional context in comments.

2 Comments

@Finnn No, flatMap transforms the Stream<Studie> to a Stream<Kurs> (your original map attempt transformed the Stream to a Stream<Set<Kurs>>).
Is it possible to output both count and print each object ?
3

Use flatMap in order to flatten your stream of Studie to stream of Kurse. Then simply .count() the items in the stream:

int count = (int) lstd.stream()                // Stream<Studie>
                      .map(Studie::getKurse)   // Stream<Set<Kurse>>
                      .flatMap(Set::stream)    // Stream<Kurse>
                      .count();                

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.