*List<String>转换为List<Integer>
List<Integer> codesInteger = codes.stream().map(Integer::parseInt).collect(Collectors.toList());
1.distinct()是Stream接口的方法。distinct()使用hashCode()和equals()方法来获取不同的元素,因此,我们的类必须实现hashCode()和equals()方法。
如:
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DistinctSimpleDemo {
public static void main(String[] args) {
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);
}
}
No. of distinct elements:3
AA,BB,CC
2.在Java 8中stream().map(),
简单的Java示例将Strings列表转换为大写,
查看以下示例:
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]
}
}
3.对象列表 - >字符串列表
从staff对象列表中获取所有属性,组成新的集合。
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]
}
}
4.
对象列表 - >其他对象列表
此示例说明如何将staff对象列表转换为对象列表StaffPublic。
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'}
]