本文主要是介绍java8——stream,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package stream;
import com.sun.imageio.plugins.common.InputStreamAdapter;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author: wu linchun
* @time: 2021/7/26 14:19
* @description: java8 stream
*/
public class Java8Test {
public static void main(String[] args) {
//filter
//初始化一个filter_list
List<String> filter_list = Arrays.asList("123", "234", "ssa", "ccd", "hhh", "", "");
//遍历输出filter_list
filter_list.forEach(System.out::println);
//过滤调filter_list中的某些值(过滤掉hhh和ccd)
List<String> filter = filter_list.stream().filter(String -> !String.equals("hhh") && !String.equals("ccd")).collect(Collectors.toList());
filter.forEach(System.out::println);
//map
List<Integer> map_list1 = Arrays.asList(1, 2, 2, 4, 5, 6);
//给map_list1中所有值*2
List<Integer> maplist = map_list1.stream().map(i -> i * 2).collect(Collectors.toList());
//给map_list1中所有值*2并过滤掉重复值
List<Integer> mapdistinctlist = map_list1.stream().map(i -> i * 2).distinct().collect(Collectors.toList());
maplist.forEach(System.out::println);
mapdistinctlist.forEach(System.out::println);
//limit
Random random = new Random();
//生成随机数并只遍历输出10个
random.ints().limit(10).forEach(System.out::println);
List<Integer> limit_list1 = Arrays.asList(1, 10, 2, 4, 5, 6);
//只取limit_list2的前三个并对这两个数进行升序排序(先取前3个值再对这3个排序)
List<Integer> limit_list2 = limit_list1.stream().limit(3).sorted().collect(Collectors.toList());
//先对limit_list2_1升序排序,再取前三个
List<Integer> limit_list2_1 = limit_list1.stream().sorted().limit(3).collect(Collectors.toList());
//用自己定义的比较器进行排序
List<Integer> limit_list3 = limit_list1.stream().sorted(new MyComparetor()).collect(Collectors.toList());
List<String> limit_list4 = Arrays.asList("a223", "tsr", "bdd", "cdd", "caa", "a122");
List<String> limit_list5 = limit_list4.stream().sorted(new MyComparetor1()).collect(Collectors.toList());
limit_list2.forEach(System.out::println);
limit_list2_1.forEach(System.out::println);
limit_list3.forEach(System.out::println);
limit_list5.forEach(System.out::println);
//sorted
Random random1 = new Random();
random1.ints().limit(10).sorted().forEach(System.out::println);
}
static class MyComparetor implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
//升序:o1-o2
//降序:o2-o1
return o1 - o2;
}
}
static class MyComparetor1 implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
//升序:o1.compareTo(o2)
//降序:o2.compareTo(o1)
return o1.compareTo(o2);
}
}
}
这篇关于java8——stream的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!