1、limit和skip截取数据
可以使用limit()
和skip()
截取流中某一段数据,例如,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Person> list1 = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
list1.stream().forEach(o->{
System.out.println("stream() :"+o.getAge());
});
//截取前n个元素
List<Person> list2 = list1.stream().limit(3).collect(Collectors.toList());
list2.stream().forEach(o->{
System.out.println("stream() limit(3):"+o.getAge());
});
//跳过前n个元素
List<Person> list3 = list1.stream().skip(3).collect(Collectors.toList());
list3.stream().forEach(o->{
System.out.println("stream() skip(3):"+o.getAge());
});
List<Person> list4 = list1.stream().skip(2).limit(2).collect(Collectors.toList());
list4.stream().forEach(o->{
System.out.println("stream() skip(2) limit(2):"+o.getAge());
});
System.exit(0); //success
}
}
2、使用sorted()排序
排序有两个方法,一是sorted()
,二是sorted(Comparator comparator)
。sorted()
使用对象的compareTo()
方法(需要实现Comparable
接口)sorted(Comparator comparator)
使用自定义的对比方法,如下,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person implements Comparable {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* 返回0,代表等于
* 返回负数,代表当前对象小于传入对象
* 返回正数,代表当前对象大于传入对象
* @param o
* @return
*/
@Override
public int compareTo(Object o) {
return getAge()-((Person)o).getAge();
}
}
public static void main(String[] args) {
//使用
ArrayList<Person> pList = new ArrayList<>();
pList.add(new Person(19));
pList.add(new Person(12));
pList.add(new Person(15));
pList.add(new Person(8));
pList.add(new Person(32));
pList.add(new Person(14));
pList.add(new Person(21));
//升序(如果想要降序,调整一下对比条件即可)
List<Person> list1 = pList.stream()
.sorted()
.collect(Collectors.toList());
list1.stream().forEach(o->{
System.out.println("stream() sort():"+o.getAge());
});
//使用自定义的排序方法
List<Person> list2 = pList.stream()
.sorted((u1, u2) -> u1.getAge() - u2.getAge())
.collect(Collectors.toList());
list2.stream().forEach(o->{
System.out.println("stream() sorted() lamdba:"+o.getAge());
});
//使用Comparator里面的方法
List<Person> list3 = pList.stream()
.sorted(Comparator.comparingInt(Person::getAge))
.collect(Collectors.toList());
list3.stream().forEach(o->{
System.out.println("stream() Comparator sorted():"+o.getAge());
});
System.exit(0); //success
}
}