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 :)

0

2 Answers 2

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.

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);
1
  • Thank you very much, your solution helped a lot :) Oct 24, 2015 at 14:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.