Java流操作——Stream(二)
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
Java流操作——Stream(一)
Java流操作——Stream(二)
文章目录
前言
本节主要介绍收集流的结果以及将流收集到映射表中
一、收集结果(collect)
//将流收集到集合中
Stream<String> words= Stream.of("ad","fa",null,"gag");
List<String> wordList =words.collect(Collectors.toList());
Set<String> wordSet =words.collect(Collectors.toSet());
TreeSet<String> wordTree =words.collect(Collectors.toCollection(TreeSet::new));
//元素之间增加分隔符
String str =words.collect(Collectors.joining(", "));
二、转化后收集结果(map.collect)
public static void main(String[] args){
User user1=new User(1,"sky",20);
User user2=new User(2,"haha",22);
User user3=new User(3,"xixi",19);
List<User> res = new ArrayList<>();
res.add(user1);
res.add(user2);
res.add(user3);
//如果流中包含字符串以外的其他对象,需要通过map进行转换,获取所有id构成的集合
List<Integer> ids=res.stream().map(User::getId).collect(Collectors.toList());
//如果流中包含字符串以外的其他对象,需要通过map全部转化为字符串,在拼接
String result= res.stream().map(User::toString).collect(Collectors.joining(", "));
}
三、将流的结果约简为总和、平均值、最大值和最小值(IntSummaryStatistics)
List<String> res= Arrays.asList("adc","agsdg","aeteq","grhrh","grhrhrhd","sgddh");
IntSummaryStatistics summaryStatistics=res.stream().collect(Collectors.summarizingInt(String::length));
//获取字符串平均长度
double averageWordLength= summaryStatistics.getAverage();
//获取最长字符串长度
double maxWordLength= summaryStatistics.getMax();
List<Integer> resInt=Arrays.asList(143,33,241,342,142);
//两种转换方法
IntSummaryStatistics summaryStatistics2=resInt.stream().mapToInt(x->x).summaryStatistics();
IntSummaryStatistics summaryStatistics3=resInt.stream().collect(Collectors.summarizingInt(x->x));
//平均值
double average=summaryStatistics2.getAverage();
double average2=summaryStatistics3.getAverage();
//最大值
double max=summaryStatistics2.getMax();
double max2=summaryStatistics3.getMax();
四、收集到映射表
1.用户类
public class User{
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.获取映射键值队(toMap)
User user = new User(1, "hah", 20);
User user2 = new User(2, "xix", 22);
User user3 = new User(3, "waw", 25);
List<User> users = Arrays.asList(user, user2, user3);
//获取id和name的键值对映射
Map<Integer,String> idNameMap=users.stream().collect(Collectors.toMap(User::getId,User::getName));
//获取id和user的映射
Map<Integer,User> idUserMap=users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
//如果多个元素具有相同的键,则会抛出IllegalStateException的异常,可以通过提供第三个函数来覆盖这种行为
//如果存在相同元素则覆盖旧元素
Map<Integer,String> idNamefilterMap=users.stream().collect(Collectors.toMap(User::getId,User::getName,(existingValue,newValue)->newValue));
五、 群组和分区(groupingBy和partitioningBy)
//获取国家对应语言的映射groupby
Stream<Locale> locale=Stream.of(Locale.getAvailableLocales());
Map<String,List<Locale>> countryToLocales=locale.collect(Collectors.groupingBy(Locale::getCountry));
System.out.println(countryToLocales.get("CH"));
Stream<Locale> locale=Stream.of(Locale.getAvailableLocales());
//获取符合条件的元素和不符合条件的元素时使用
Map<Boolean,List<Locale>> englishAndOtherLocales=locale.collect(Collectors.partitioningBy(l->l.getLanguage().equals("en")));
List<Locale> englishLocales=englishAndOtherLocales.get(true);
List<Locale> otherLocales=englishAndOtherLocales.get(false);
六、下游收集器
Stream<Locale> locale=Stream.of(Locale.getAvailableLocales());
//获取符合条件的元素和不符合条件的元素时使用
Map<Boolean,List<Locale>> englishAndOtherLocales=locale.collect(Collectors.partitioningBy(l->l.getLanguage().equals("en")));
List<Locale> englishLocales=englishAndOtherLocales.get(true);
List<Locale> otherLocales=englishAndOtherLocales.get(false);
//counting会产生收集到元素的个数
Map<String,Long> localeToLocaleCounts=locale.collect(Collectors.groupingBy(Locale::getCountry,Collectors.counting()));
//summing(int/long/double)会接受一个函数作为引元将该函数应用到下游元素中,并产生他们的和
Map<String,Integer> localeToLanguage=locale.collect(Collectors.groupingBy(Locale::getCountry,Collectors.summingInt(x->x.getLanguage().length())));
//maxBy和minBy会接受一个比较器,并产生下游元素中的最大值和最小值
Map<String,Optional<Locale>> stateToLocales=locale.collect(Collectors.groupingBy(Locale::getCountry,Collectors.maxBy(Comparator.comparing(x->x.getLanguage().length()))));
//mapping方法会产生将函数应用到下游结果上的收集器
Map<String,Optional<String>> stateToLocalesMapping=locale.collect(Collectors.groupingBy(Locale::getCountry,Collectors.mapping(Locale::getLanguage,Collectors.maxBy(Comparator.comparing(String::length)))));
Map<String,Set<String>> languageToLocalesMapping=locale.collect(Collectors.groupingBy(Locale::getCountry,Collectors.mapping(Locale::getLanguage,Collectors.toSet())));
//如果群组和映射函数的返回值为int、long或double,那么可以从每个分组获取这些函数值的总和、个数、平均值、最大值
Map<String,IntSummaryStatistics> languageToCountry=locale.collect(Collectors.groupingBy(Locale::getCountry,Collectors.summarizingInt(x->x.getLanguage().length())));
版权声明:本文为s13073660520原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。