Best way to avoid redundant code while creating multiple new objects

Philipp :

I try to get my head around functional Java and streams.

For example one way to create new object with just a small difference in the name would be:

List<NewTopic> topicList = new ArrayList<NewTopic>();

for (Event event : events) {
           System.out.println(events.toString());
           topicList.add(new NewTopic(event.getName() + "-in", 1, (short) 1)); 
           topicList.add(new NewTopic(event.getName() + "-out", 1, (short) 1)); 
           topicList.add(new NewTopic(event.getName() + "-err", 1, (short) 1)); 
}

Instead of crating three objects in three lines a nested loop with an extra array of strings ("in", "out", "err") would be possible.

Now with streams something like this should be possible:

List<NewTopic> topicList = new ArrayList<NewTopic>();
String[] topicNames = {"-in", "-out", "-err"};

events.forEach(
       event -> Arrays.stream(topicNames).forEach(
                ending -> topicList.add(
                       new NewTopic(event.getName()
                               + ending, 1, (short) 1)
                    )
           )
);        

Is there are more elegant + shorter way to do this?

Thanks!

Lino :

You were close, instead of using foreach to add to an existing List you should use a Collector:

String[] topicNames = {"-in", "-out", "-err"};
List<NewTopic> topicList = events.stream()
    .flatMap(event -> Arrays.stream(topicNames)
        .map(ending -> event.getName() + ending)
    )
    .map(name -> new NewTopic(name, 1, (short) 1))
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334408&siteId=1