Home > database >  Print a field of a list of protobuf messages in java
Print a field of a list of protobuf messages in java

Time:01-12

I have a protobuf message foo with some fields including id field which is uint32.

message foo {
uint32 foo_id = 1;
bool committed = 2;
...
}

In my main class and main function, I have a list of foos: List<foo> foos. I want to printout the foo_ids of all foos in line. I know there is straight forward for loop option as follows but was wondering if there is any clean lambda way of doing it.

I tried

String s = "The list of ids are: "
for(i = 0; i < foos.size(); i  ) {
   s = s   Integer.toString(foos.get(i).getFooId());
}
System.out.println(s);

but I'm expecting a better and cleaner way.

CodePudding user response:

If you want to use lambda (or like python way), you must know the stream() apis (possibly and the google's guava lib).

// guava 
import com.google.common.base.Joiner;

System.out.println(Joiner.on(",").join(
    foos.stream().map(foo::getFooId).map(String::valueOf).iterator()
));
  • Related