1

I have written a following code in imperative style that is working fine . but i want to convert it to java 8 , I have tried it but could not able to get in most elegant way .

List<Wrapper> futureList = new ArrayList<>();
List<Wrapper> pastList = new ArrayList<>();
List<Wrapper> list = fooRepository.findAll();
for(Wrapper data : list){
  if(data.getSchedule().toInstant().isAfter(new Date().toInstant())
       futureList.add(data);
   else
       pastList.add(data);     
 } 

1 Answer 1

3

Well, the easiest thing to do if you want to use Streams is using Collectors.partitioningBy like that:

Map<Boolean, List<Wrapper>> map = list.stream()
        .collect(Collectors.partitioningBy(data -> data.getSchedule().toInstant().isAfter(Instant.now())));
List<Wrapper> pastList = map.get(false);
List<Wrapper> futureList = map.get(true);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks . where from i can learn this type of techniques in java 8 ?
Just Google "java stream tutorial" - the very first result (Java 8 Stream Tutorial) looks quite promising. Later on, consult the JavaDocs: java.util.stream, Stream, Collectors classes.

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.