stream方法获取指向当前Collection对象的流对象,filter将对流中元素进行过滤,结合lambda表达式,需要在filter参数中实现一个类似于比较器的Predicate对象,返回一个boolean类型返回值,只有返回为true的Collection中的元素才会进入到forEach的循环中。
List 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 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 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);
在此示例中,我们有一个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 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()));
distinct()不提供按照属性对对象列表进行去重的直接实现。它是基于hashCode()和equals()工作的。如果我们想要按照对象的属性,对对象列表进行去重,我们可以通过其它方法来实现。如下代码段所示:
static Predicate distinctByKey(Function super T, ?> keyExtractor) {
Map
上面的方法可以被Stream接口的 filter()接收为参数,如下所示:
list.stream().filter(distinctByKey(b -> b.getName()));
distinctByKey()方法返回一个使用ConcurrentHashMap 来维护先前所见状态的 Predicate 实例,如下是一个完整的使用对象属性来进行去重的示例。
public class DistinctByProperty {
public static void main(String[] args) {
List 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 Predicate distinctByKey(Function super T, ?> keyExtractor) {
Map
Map 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 entry : items.entrySet()) {
System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
}
Map 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");
}
});
https://www.mkyong.com/java8/java-8-streams-map-examples/
public class TestJava8 {
public static void main(String[] args) {
List alpha = Arrays.asList("a", "b", "c", "d");
//Before Java8
List 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 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 num = Arrays.asList(1,2,3,4,5);
List 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 = 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 result = new ArrayList<>();
for (Staff x : staff) {
result.add(x.getName());
}
System.out.println(result); //[mkyong, jack, lawrence]
//Java 8
List 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 = Arrays.asList(
new Staff("mkyong", 30, new BigDecimal(10000)),
new Staff("jack", 27, new BigDecimal(20000)),
new Staff("lawrence", 33, new BigDecimal(30000))
);
List result = convertToStaffPublic(staff);
System.out.println(result);
}
private static List convertToStaffPublic(List staff) {
List 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 = 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 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'}
]