标签:sep 学习java optional turn int max system rri int()
1.流
得到流 Stream<T>stream = collection.stream();
对于数组 : Arrays.sstream(ary)
对于collection : 用list.stream()
import java.util.*;
class streamList {
public static void main(String... args) {
Collection<Person> people = Arrays.asList(
new Person("Ted", 18, 88),
new Person("Charlotte", 18, 88),
new Person("Michael", 18, 99),
new Person("Matthew", 19, 84),
new Person("Matthew", 21, 84)
);
Object result =
people.parallelStream()
.filter( p -> p.age<20 )
.sorted( (p1,p2)->p1.age-p2.age)
.sorted( Person::better)
.sorted( Comparator.comparing( Person::getName ) )
.limit(5)
.mapToDouble( p -> p.score )
.average();
System.out.println(result);
}
}
class Person
{
public String name;
public int age;
public double score;
public Person(String n, int a, double s) {
name = n; age = a; score = s;
}
public String getName(){ return name;}
@Override
public String toString() {
return String.format("%s[%d](%f)", name,age,score);
}
public static int better(Person p1, Person p2) {
return (int)(p2.score - p1.score);
}
}
对于map : 没有流,有相似方法
map.merge
*数组进行流化
Arrays.stream(a)
.filter(i -> i < 20)
.map(i -> i*i)
.max();
import java.util.*;
class streamArray
{
public static void main(String[] args)
{
int [] a = new int[100];
for(int i=0; i<a.length; i++)
a[i] = (int)(Math.random()*100);
OptionalInt result=
Arrays.stream(a).parallel()
.filter( i -> i>20 )
.map( i -> i*i )
.sorted()
.distinct()
.limit(10)
.max();
System.out.println(
result.isPresent()? "最大值为"+result.getAsInt(): "无值");
}
}
2.并行的流式操作
import java.util.*;
class UseParallelStream
{
public static void main(String[] args)
{
List<Integer> a = Arrays.asList(1,2,5,7,3);
System.out.println(
a.parallelStream()
.mapToInt(i->(int)i)
.filter( i -> i>2 )
.map( i -> i*i )
.sorted()
.distinct()
.limit(10)
.max()
);
}
}
明天学习内容:
输入输出流
学习java第22天
标签:sep 学习java optional turn int max system rri int()
原文地址:https://www.cnblogs.com/SirNie/p/13386377.html