Java8中使用stream()、filter()、forEach()、collect、distinct、map()
stream方法获取指向当前Collection对象的流对象,filter将对流中元素进行过滤,结合lambda表达式,需要在filter参数中实现一个类似于比较器的Predicate对象,返回一个boolean类型返回值,只有返回为true的Collection中的元素才会进入到forEach的循环中。List<String> strArr = Arrays.asList(...
stream方法获取指向当前Collection对象的流对象,filter将对流中元素进行过滤,结合lambda表达式,需要在filter参数中实现一个类似于比较器的Predicate对象,返回一个boolean类型返回值,只有返回为true的Collection中的元素才会进入到forEach的循环中。
List<String> strArr = Arrays.asList("21", "22", "3", "4");
strArr.stream().filter(str ->{
return str.startsWith("2");
}).filter(str ->{
return str.equals("22");
}).forEach(str ->{
System.out.println(str);
});
使用collect将stream转化为list
List<String> result1 = lines.stream() // convert list to stream
.filter(line -> !"mkyong".equals(line)) // filter the line which equals to "mkyong"
.collect(Collectors.toList()); // collect the output and convert streams to a list
result1.forEach(System.out::println); // o
Stream.distinct() :字符串去重
List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
long l = list.stream().distinct().count();
System.out.println("No. of distinct elements:"+l);
String output = list.stream().distinct().collect(Collectors.joining(","));
System.out.println(output);
2. Stream.distinct() with List of Objects
在此示例中,我们有一个Book对象列表。 为了对列表进行去重,该类将重写hashCode()和equals()。
public class Book {
private String name;
private int price;
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
final Book book = (Book) obj;
if (this == book) {
return true;
} else {
return (this.name.equals(book.name) && this.price == book.price);
}
}
@Override
public int hashCode() {
int hashno = 7;
hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
return hashno;
}
}
List<Book> list = new ArrayList<>();
{
list.add(new Book("Core Java", 200));
list.add(new Book("Core Java", 200));
list.add(new Book("Learning Freemarker", 150));
list.add(new Book("Spring MVC", 300));
list.add(new Book("Spring MVC", 300));
}
long l = list.stream().distinct().count();
System.out.println("No. of distinct books:"+l);
list.stream().distinct().forEach(b -> System.out.println(b.getName()+ "," + b.getPrice()));
3. Distinct by Property
distinct()不提供按照属性对对象列表进行去重的直接实现。它是基于hashCode()和equals()工作的。如果我们想要按照对象的属性,对对象列表进行去重,我们可以通过其它方法来实现。如下代码段所示:
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
上面的方法可以被Stream接口的 filter()接收为参数,如下所示:
list.stream().filter(distinctByKey(b -> b.getName()));
distinctByKey()方法返回一个使用ConcurrentHashMap 来维护先前所见状态的 Predicate 实例,如下是一个完整的使用对象属性来进行去重的示例。
public class DistinctByProperty {
public static void main(String[] args) {
List<Book> list = new ArrayList<>();
{
list.add(new Book("Core Java", 200));
list.add(new Book("Core Java", 300));
list.add(new Book("Learning Freemarker", 150));
list.add(new Book("Spring MVC", 200));
list.add(new Book("Hibernate", 300));
}
list.stream().filter(distinctByKey(b -> b.getName()))
.forEach(b -> System.out.println(b.getName()+ "," + b.getPrice()));
}
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
Foreach 使用(map)
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
for (Map.Entry<String, Integer> entry : items.entrySet()) {
System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
}
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
items.forEach((k,v)->{
System.out.println("Item : " + k + " Count : " + v);
if("E".equals(k)){
System.out.println("Hello E");
}
});
map()
https://www.mkyong.com/java8/java-8-streams-map-examples/
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. List of objects -> List of String
2.1 Get all the name values from a list of the staff objects.
Staff.java
package com.mkyong.java8;
import java.math.BigDecimal;
public class Staff {
private String name;
private int age;
private BigDecimal salary;
//...
}
Copy
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]
}
}
Copy
3. List of objects -> List of other objects
3.1 This example shows you how to convert a list of staff objects into a list of StaffPublic objects.
Staff.java
package com.mkyong.java8;
import java.math.BigDecimal;
public class Staff {
private String name;
private int age;
private BigDecimal salary;
//...
}
Copy
StaffPublic.java
package com.mkyong.java8;
public class StaffPublic {
private String name;
private int age;
private String extra;
//...
}
Copy
3.2 Before 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;
}
}
Copy
Output
[
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'}
]
Copy
3.3 Java 8 example.
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);
}
}
Copy
Output
[
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'}
]
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)