内容简介 本文主要说明在Java8及以上版本中,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合。 List对象类(StudentInfo)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
public class StudentInfo implements Comparable<StudentInfo> { //名称 private String name; //性别 true男 false女 private Boolean gender; //年龄 private Integer age; //身高 private Double height; //出生日期 private LocalDate birthday; public StudentInfo(String name, Boolean gender, Integer age, Double height, LocalDate birthday){ this.name = name; this.gender = gender; this.age = age; this.height = height; this.birthday = birthday; } public String toString(){ String info = String.format("%s\t\t%s\t\t%s\t\t\t%s\t\t%s",this.name,this.gender.toString(),this.age.toString(),this.height.toString(),birthday.toString()); return info; } public static void printStudents(List<StudentInfo> studentInfos){ System.out.println("[姓名]\t\t[性别]\t\t[年龄]\t\t[身高]\t\t[生日]"); System.out.println("----------------------------------------------------------"); studentInfos.forEach(s->System.out.println(s.toString())); System.out.println(" "); } @Override public int compareTo(StudentInfo ob) { return this.age.compareTo(ob.getAge()); //return 1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getGender() { return gender; } public void setGender(Boolean gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public LocalDate getBirthday() { return birthday; } public void setBirthday(LocalDate birthday) { this.birthday = birthday; } } |
测试数据
1 2 3 4 5 6 |
//测试数据,请不要纠结数据的严谨性 List<StudentInfo> studentList = new ArrayList<>(); studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23))); studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3))); studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11))); studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18))); |
输出Students列表
1 2 |
//输出List StudentInfo.printStudents(studentList); |
输出结果如下图: 使用filter()过滤List
1 2 3 4 |
//查找身高在1.8米及以上的男生 List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList()); //输出查找结果 StudentInfo.printStudents(boys); |
结果如下图: from:https://www.cnblogs.com/codecat/p/10912454.html
View DetailsAPI: https://www.runoob.com/java/java8-streams.html
1 2 3 4 |
mylist.stream() .map(myfunction->{ return item; }).collect(Collectors.toList()); |
说明: steam():把一个源数据,可以是集合,数组,I/O channel, 产生器generator 等,转化成流。 forEach():迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数.
1 2 |
Random random = new Random(); random.ints().limit(10).forEach(System.out::println); |
map():用于映射每个元素到对应的结果。以下代码片段使用 map 输出了元素对应的平方数:
1 2 3 |
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); // 获取对应的平方数 List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); |
filter():filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串:
1 2 3 4 5 6 7 8 |
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); // 获取空字符串的数量 int count = strings.stream().filter(string -> string.isEmpty()).count(); limit limit 方法用于获取指定数量的流。 以下代码片段使用 limit 方法打印出 10 条数据: Random random = new Random(); random.ints().limit(10).forEach(System.out::println); |
sorted(): 用于对流进行排序。以下代码片段使用 sorted 方法对输出的 10 个随机数进行排序:
1 2 3 4 5 6 7 8 9 |
Random random = new Random(); random.ints().limit(10).sorted().forEach(System.out::println); 并行(parallel)程序 parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量: List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); // 获取空字符串的数量 int count = strings.parallelStream().filter(string -> string.isEmpty()).count(); 我们可以很容易的在顺序运行和并行直接切换。 |
Collectors(): 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:
1 2 3 4 5 6 |
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); System.out.println("筛选列表: " + filtered); String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); System.out.println("合并字符串: " + mergedString); |
from:https://blog.csdn.net/shine_guo_star/article/details/94383319
View Details转: https://blog.csdn.net/sanchan/article/details/70753645 java8的optional的使用: http://www.jdon.com/idea/java/using-optional-effectively-in-java-8.html http://www.runoob.com/java/java8-optional-class.html Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。 Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。 Optional 类的引入很好的解决空指针异常。 类声明 以下是一个 java.util.Optional<T> 类的声明: public final class Optional<T> extends Object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
在Java 8中stream().map(),您可以将对象转换为其他对象。查看以下示例: 1.大写字符串列表 1.1简单的Java示例将Strings列表转换为大写。 TestJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TestJava8 { public static void main(String[] args) { List<String> alpha = Arrays.asList("a", "b", "c", "d"); //Before Java8 List<String> alphaUpper = new ArrayList<>(); for (String s : alpha) { alphaUpper.add(s.toUpperCase()); } System.out.println(alpha); //[a, b, c, d] System.out.println(alphaUpper); //[A, B, C, D] // Java 8 List<String> collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println(collect); //[A, B, C, D] // Extra, streams apply to any data type. List<Integer> num = Arrays.asList(1,2,3,4,5); List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList()); System.out.println(collect1); //[2, 4, 6, 8, 10] } } 2.对象列表 - >字符串列表 2.1 name从staff对象列表中获取所有值。 Staff.java package com.mkyong.java8; import java.math.BigDecimal; public class Staff { private String name; private int age; private BigDecimal salary; //... } TestJava8.java package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TestJava8 { public static void main(String[] args) { List<Staff> staff = Arrays.asList( new Staff("mkyong", 30, new BigDecimal(10000)), new Staff("jack", 27, new BigDecimal(20000)), new Staff("lawrence", 33, new BigDecimal(30000)) ); //Before Java 8 List<String> result = new ArrayList<>(); for (Staff x : staff) { result.add(x.getName()); } System.out.println(result); //[mkyong, jack, lawrence] //Java 8 List<String> collect = staff.stream().map(x -> x.getName()).collect(Collectors.toList()); System.out.println(collect); //[mkyong, jack, lawrence] } } 对象列表 - >其他对象列表 3.1此示例说明如何将staff对象列表转换为对象列表StaffPublic。 Staff.java package com.mkyong.java8; import java.math.BigDecimal; public class Staff { private String name; private int age; private BigDecimal salary; //... } StaffPublic.java package com.mkyong.java8; public class StaffPublic { private String name; private int age; private String extra; //... } 3.2 Java 8之前。 BeforeJava8.java package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BeforeJava8 { public static void main(String[] args) { List<Staff> staff = Arrays.asList( new Staff("mkyong", 30, new BigDecimal(10000)), new Staff("jack", 27, new BigDecimal(20000)), new Staff("lawrence", 33, new BigDecimal(30000)) ); List<StaffPublic> result = convertToStaffPublic(staff); System.out.println(result); } private static List<StaffPublic> convertToStaffPublic(List<Staff> staff) { List<StaffPublic> result = new ArrayList<>(); for (Staff temp : staff) { StaffPublic obj = new StaffPublic(); obj.setName(temp.getName()); obj.setAge(temp.getAge()); if ("mkyong".equals(temp.getName())) { obj.setExtra("this field is for mkyong only!"); } result.add(obj); } return result; } } 输出 [ StaffPublic{name='mkyong', age=30, extra='this field is for mkyong only!'}, StaffPublic{name='jack', age=27, extra='null'}, StaffPublic{name='lawrence', age=33, extra='null'} ] 1 2 3 4 5 3.3 Java 8的例子。 NowJava8.java package com.mkyong.java8; package com.hostingcompass.web.java8; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class NowJava8 { public static void main(String[] args) { List<Staff> staff = Arrays.asList( new Staff("mkyong", 30, new BigDecimal(10000)), new Staff("jack", 27, new BigDecimal(20000)), new Staff("lawrence", 33, new BigDecimal(30000)) ); // convert inside the map() method directly. List<StaffPublic> result = staff.stream().map(temp -> { StaffPublic obj = new StaffPublic(); obj.setName(temp.getName()); obj.setAge(temp.getAge()); if ("mkyong".equals(temp.getName())) { obj.setExtra("this field is for mkyong only!"); } return obj; }).collect(Collectors.toList()); System.out.println(result); } } [ StaffPublic{name='mkyong', age=30, extra='this field is for mkyong only!'}, StaffPublic{name='jack', age=27, extra='null'}, StaffPublic{name='lawrence', age=33, extra='null'} ] |
from:https://www.cnblogs.com/fengli9998/p/9002377.html
View Details