Total Pageviews

2016/10/10

[Java 8] Using lambda to convert a List of object to comma-separated string

If I java an object which named Group
1
2
3
4
5
6
7
    import lombok.Data;
    
    @Data
    public class Group {    
        private Integer id;
        private String name;
    }

The data in List of Group looks like:
1
2
3
    Group(id=1, name=Group A)
    Group(id=2, name=Group B)
    Group(id=3, name=Group C)

The expected result is to convert to comma-separated string: 
Group A, Group B, Group c

If we does not utilize lambda expression, the code snippet is as following:
1
2
3
4
5
6
7
8
9
    List<Group> groups = dto.getUser().getGroups();
    StringBuilder groupStringBuilder = new StringBuilder();
    for (int i = 0; i < groups.size(); i++) {
        if (i == groups.size() - 1) {
            groupStringBuilder = groupStringBuilder.append(groups.get(i).getName());
        } else {
            groupStringBuilder = groupStringBuilder.append(groups.get(i).getName()).append(", ");
        }
    }


If we apply lambda expression, we only need to use one line of code to meet this requirement:
    String groupStr = groups.stream().map(g -> g.getName()).collect(Collectors.joining(", "));




No comments: