0

I have got a little problem with printing out comma in my java project. In forEach section the program is always printing out "," > even after the last word... see output

.listener("lookAround", (Game g, String action, AbstractGameObject object, Object retVal) -> {
    System.out.print("You see: \n\t");

    if (g.getItemsInRoom((Room) object).isEmpty() && g.getDoorsInRoom((Room) object).isEmpty())
       System.out.print("nothing");

    g.getItemsInRoom((Room) object)
                     .stream()
                     .forEach(item -> System.out.print(item.getName() + ", "));

    g.getDoorsInRoom((Room) object)
                     .stream()
                     .forEach(door -> System.out.print(door.getName() + ", "));
    System.out.println("\n");
})

The output:

You see:    
Black Wooden door, Brown Wooden door,

I would like output:

You see:    
Black Wooden door, Brown Wooden door

Is there a easy way to solve this problem ? Thank you for a help :)

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Kolos Fuchs
  • 47
  • 1
  • 8

2 Answers2

3

I don't think you should be printing inside that forEach lambda. Actually I'm not even sure you should be using the stream API there.

Think about using String.join() or the StringJoiner class instead.

Wormbo
  • 4,978
  • 2
  • 21
  • 41
1

Using a StringJoiner directly, rather than via the Stream API, let’s you handle the empty case without additional code:

StringJoiner j=new StringJoiner(", ").setEmptyValue("nothing");
g.getItemsInRoom((Room)object).forEach(o -> j.add(o.getName()));
g.getDoorsInRoom((Room)object).forEach(o -> j.add(o.getName()));
System.out.println("You see: \n\t"+j);
Holger
  • 285,553
  • 42
  • 434
  • 765