Playing with Streams

The One Line Solution

Hi! Guyz, I just amazed by a example during my learning of java8 stream API let me tell you.
Earlier if I have a list of objects and I want them to be filtered and made groups of no of objects on basis of some property of Object. I used to follow the approach shown below and now I started using new approach which is also shown below.

public class Task{

private String status;
private Integer point;
....

public Task(String status,Integer point){
   this.status = status;
   this.point = point;
}

//getter  & setter

And collection of Tasks. And I want to Group all Task on the basis of status.

Earlier Approach:

List<Task> tasks = Arrays.asList(
   new Task("OPEN",10),new Task("CLOSED",20)........)
Map<String,List<Task>> earlier = new HashMap<String,<List<Task>>>();
for(Task task : tasks){
    List<Task> tasks = earlier.get(task.getStatus());
    if(tasks==null){
      tasks = new ArrayList<Task>();
       earlier.put(task.getStatus(),tasks);
    }
    tasks.add(task);
}

New Approach using Stream API:

Map<String,List<Tasks>> newMap = tasks
       .parallelStream()
       .collect(Collectors.groupingBy(Task::getStatus));

Thats It! It is done.

If you are also doing same as old. Here is new way adapt it now 🙂 .

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: