1

In my taks I need to find size() of argument and for every object print size. Object of type Car are in Set(so this maybe should help)

I did this:

List<Integer> numberOf = cars
.stream
.map(car->car.getNumbers().size())
.collect(Collectors.toList());

System.out.println(numberOf);

Output is : [1,1,1,1]

I need output like this:

Audi - 1 Bmw - 1 Porsche - 1 Bentley - 1

If I go with

for(Car c: cars)
sout(c.getName + numberOf)

It gets me Audi [1,1,1,1] Bmw[1,1,1,1]etc.

How to properly print all those values. I also tried to Override method toString in class car but I also get the same output.

Edit: Class Car

public Car(String name, List<Colours> colours)
super(name);
this.colours= colours;
sdavb
  • 31
  • 7

2 Answers2

0

The simplest solution is:

    cars.forEach(car -> 
            System.out.println(car.getName() + " - " + car.getNumbers().size()));

Grouping by name:

import java.util.stream.Collectors;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;


Collection<Car> cars = ...// your cars
final Map<String, Long> grouped = 
    cars.stream()
        .collect(groupingBy(car -> car.getName(), counting()));
System.out.println(grouped);
Jackkobec
  • 5,889
  • 34
  • 34
0

If you want output like "name - number", perhaps generate strings:

List<String> combined = cars
.stream
.map(car->car.getName + " - " + car.getNumbers().size())
.collect(Collectors.toList());

System.out.println(combined);
tevemadar
  • 12,389
  • 3
  • 21
  • 49