本篇文章介绍 Java 8 API 中常用方法
文章中如有不清楚的,或者是没有你需要实现的代码实例,欢迎进行留言!
public class T {
@Data
@Builder
public static class City {
private Long id;
private String name;
private Integer count;
}
public static void main(String[] args) {
List<City> citys = Lists.newArrayList();
citys.add(City.builder().id(Long.valueOf(1)).name("北京").count(100000).build());
citys.add(City.builder().id(Long.valueOf(2)).name("上海").count(300000).build());
citys.add(City.builder().id(Long.valueOf(3)).name("广州").count(500000).build());
citys.add(City.builder().id(Long.valueOf(4)).name("深圳").count(700000).build());
boolean isExist1 = citys.stream().anyMatch(city -> city.getName().equals("北京"));
boolean isExist2 = citys.stream().allMatch(city -> city.getName().equals("北京"));
citys.stream().forEach(city -> {
System.err.println(city.name);
});
List<City> list1 = citys.stream().filter(city -> city.count > 300000).collect(Collectors.toList());
Map<String, City> map1 = citys.stream().collect(Collectors.toMap(City::getName, Function.identity()));
Map<String, City> map2 = citys.stream().collect(Collectors.toMap(City::getName, v -> v));
Map<String, Integer> map3 = citys.stream().collect(Collectors.toMap(City::getName, v -> v.getCount()));
Map<String, Integer> map4 = citys.stream().collect(Collectors.toMap(City::getName, City::getCount));
Map<String, City> map5 = citys.stream().collect(Collectors.toMap(City::getName, v -> v, (oldValue, newValue) -> newValue));
List<City> list2 = citys.stream().distinct().collect(Collectors.toList())
IntSummaryStatistics intSummaryStatistics = citys.stream().mapToInt((c) -> c.count).summaryStatistics();
System.err.println("最大值:" + intSummaryStatistics.getMax());
System.err.println("最小值:" + intSummaryStatistics.getMin());
System.err.println("总和:" + intSummaryStatistics.getSum());
System.err.println("平均值:" + intSummaryStatistics.getAverage());
System.err.println("总条数:" + intSummaryStatistics.getCount());
List<Integer> list3 = citys.stream().map(City::getCount).collect(Collectors.toList());
List<City> list4 = citys.stream().sorted(Comparator.comparing(City::getCount).reversed()).collect(Collectors.toList());
List<City> list5 = citys.stream().limit(3).collect(Collectors.toList());
Map<Long, List<City>> map6 = citys.stream().collect(Collectors.groupingBy(City::getId));
}
}