Sort a Java List with Specific Fields

By
In this tutorial, we will discuss about sorting a list by specific field/property. Often, we need to sort a list with its specific field. This is very easy and short code in java 8. Let's go for details...

Example:

1:  package com.javabd1.blogspot.controller;  
2:  import java.util.ArrayList;  
3:  import java.util.HashMap;  
4:  import java.util.List;  
5:  import java.util.Map;  
6:  import org.springframework.beans.factory.annotation.Autowired;  
7:  import org.springframework.stereotype.Controller;  
8:  import org.springframework.validation.BindingResult;  
9:  import org.springframework.web.bind.annotation.ModelAttribute;  
10:  import org.springframework.web.bind.annotation.RequestMapping;  
11:  import org.springframework.web.bind.annotation.RequestMethod;  
12:  import org.springframework.web.servlet.ModelAndView;  
13:  /**  
14:   * @author Ferdous Islam  
15:   *  
16:   */  
17:  @Controller  
18:  public class EmployeeController {  
19:   @Autowired  
20:   private EmployeeService employeeService;  
21:   @RequestMapping(value="/employees", method = RequestMethod.GET)  
22:   public ModelAndView listEmployees() {  
23:   Map<String, Object> model = new HashMap<String, Object>();  
24:   List<Employee> empList=employeeService.listEmployeess();  
25:   empList.sort(Comparator.comparing(Employee::getName()));  
26:    model.put("employees", empList );  
27:    return new ModelAndView("employeesList", model);  
28:   }  
29:  }
Note: Here, the list sorted with name field, you may sort it with any other field.


This may Work Fine!!

Visit this blog for more solution of various problem...


0 comments:

Post a Comment