0

I have a class that has a list of Events.

public class EventScheduler{

     List<Event> event

}

public class Event{

     private String text;
     private int timestamp;

}

I have an EventView, it takes an Event as a constructor and has getters and no setters.

It is basically allows subset of variables set in event to be viewed, whilst acting in a similar fashion to Event.

public class EventView{

     public EventView(Event event){
         this.event = event;
     }

     public String getText(){
         return event.getText();
     }

     //no timestamp getter as its not allowed for this view object.
}

So with this setup, what is the quickest way to convert a List<Event> to List<EventView>? Or some kind of alternative.

2
  • as answered below, you have to instantiate an object using "new". Commented Sep 10, 2014 at 11:55
  • You write a for-loop that iterators over the list of Events and creates en EventView object for each. With Java 8 there are alternative syntaxes than a for-loop to do the same. Commented Sep 10, 2014 at 11:55

2 Answers 2

4

With Java 8:

List<EventView> views = events.stream()
                              .map(EventView::new)
                              .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

3

Iterate over each Event and create an EventView for it, then pass it to a list:

List<EventView> eventViewList = new ArrayList<EventView>();
if(eventList != null) {
   for(Event event : eventList) {
       EventView eventView = new EventView(event);
       eventViewList.add(eventView);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.