importlombok.Data;import java.util.*;importjava.util.stream.Collectors;public classTestMain {//测试集合
private List newsList = new ArrayList<>();public static voidmain(String[] args) {
TestMain testMain= newTestMain();//初始集合
List initList =testMain.newsList;//待赋值集合
List otherList = new ArrayList<>();//单个属性排序,按title字符串排序
List titleSortList =initList.stream().sorted(paring(News::getTitle)).collect(Collectors.toList());//多个属性排序, 按title、author字符串排序 thenComparing可以多个...
List titleAndAuthorSortList =initList.stream().sorted(paring(News::getTitle)
.thenComparing(paring(News::getAuthor)))
.collect(Collectors.toList());//多个属性排序, 按title、hitNum倒序
List titleAndHitsSortList =initList.stream().sorted(paring(News::getTitle)
.thenComparing(paring(News::getHits).reversed()))
.collect(Collectors.toList());//多个属性排序,按title、hot排序降序,hot需转成数字进行排序
List titleAndHotSortList =initList.stream().sorted(paring(News::getTitle)
.thenComparing((v1, v2)->Integer.valueOf(v2.getHot()).compareTo(Integer.valueOf(v1.getHot()))))
.collect(Collectors.toList());//集合过滤,hot大于30的数据
List hotFilterList = initList.stream().filter(news -> news.getHits() > 30).collect(Collectors.toList());//按照title/content字段进行去重
List titleRepeatList =initList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
()-> new TreeSet<>(paring(o -> o.title +o.content))),
ArrayList::new));//从 List 中取出title属性的组成 新的list 集合
List titleList =initList.stream().map(News::getTitle).collect(Collectors.toList());//List转Map key:title,value:content;使用去重后的集合防止key不唯一
Map titleAndContentMap = titleRepeatList.stream().collect(Collectors.toMap(o -> o.getTitle(), o ->o.getContent()));//单个属性分组,title分组
Map> titleMap =initList.stream().collect(Collectors.groupingBy(News::getTitle));//多个属性分组,title、author分组,groupingBy可以为多个
Map>> titleAndAuthorMap =initList.stream().collect(Collectors.groupingBy(News::getTitle, Collectors.groupingBy(News::getAuthor)));//利用stream().map()处理List,并给另外一个List赋值
otherList = initList.stream().map(news -> {returnnews;}).collect(Collectors.toList());//list遍历
initList.forEach(news ->{
System.out.println(news.getContent());
});//map遍历
titleAndAuthorMap.forEach((k,v) ->{
System.out.println(k);
Map> map =v;
});
}//代码块初始化数据
{int i = 50;while (i > 0) {//1-5随机数
int num = (int) (Math.random() * 5 + 1);//1-50随机数
int hitNum = (int) (Math.random() * 50 + 1);//1-500随机数
int hotNum = (int) (Math.random() * 500 + 1);
News news= newNews();
news.setTitle("title" +num);
news.setAuthor("author" +num);
news.setContent("content" +num);
news.setHits(hitNum);
news.setHot(hotNum+ "");
newsList.add(news);
i--;
}
}/*** 测试内部类*/@DataclassNews {//标题
privateString title;//作者
privateString author;//内容
privateString content;//点击数
private inthits;//热度
privateString hot;
}
}