需求:获取同一个分类下面的某个字段,去重后,拼接成字符,用逗号分隔。
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;
public class Test {
public static void main(String[] args) {
List<BlogPost> list = new ArrayList<BlogPost>();
BlogPost temp1 = new BlogPost("a1","b1","1",1);
BlogPost temp2 = new BlogPost("a1","b1","1",1);
BlogPost temp3 = new BlogPost("a2","b2","1",1);
BlogPost temp4 = new BlogPost("a3","b2","3",1);
BlogPost temp5 = new BlogPost("a4","b3","5",1);
list.add(temp1);
list.add(temp2);
list.add(temp3);
list.add(temp4);
list.add(temp5);
// Map<String, String> postsPerType = list.stream()
// .collect(groupingBy(BlogPost::getType,
// mapping(BlogPost::getTitle, joining(", ", "[", "]"))));
// System.out.println(postsPerType.get("1"));
Map<String, Set<String>> postsPerType = list.stream()
.collect(groupingBy(BlogPost::getType,
Collectors.mapping(BlogPost::getTitle, Collectors.toSet())));
System.out.println(postsPerType.get("4"));
}
}
@Data
class BlogPost {
String title;
String author;
String type;
int likes;
BlogPost(String title,String author,String type,int likes){
this.title = title;
this.author = author;
this.type = type;
this.likes = likes;
}
}