Stream
方法介绍
List
Map
Array
optional
lamda
常用方法
toc
Stream
Java8 Stream 使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合进行链状流式的操作。
方法介绍
#filter():对流的元素过滤
List<PersonModel> collect1 = data.stream().filter(person -> ("男".equals(person.getSex())&&person.getAge()<20)).collect(toList());
#map():将流的元素映射成另一个类型
List<String> collect = data.stream().map(person -> person.getName()).collect(toList());
* collect在流中生成列表,map,等常用的数据结构
/**
* toList
*/
public static void toListTest(){
List<PersonModel> data = Data.getData();
List<String> collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toList());
}
/**
* toSet
*/
public static void toSetTest(){
List<PersonModel> data = Data.getData();
Set<String> collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toSet());
}
/**
* toMap
*/
public static void toMapTest(){
List<PersonModel> data = Data.getData();
Map<String, Integer> collect = data.stream()
.collect(
Collectors.toMap(PersonModel::getName, PersonModel::getAge)
);
data.stream()
.collect(Collectors.toMap(per->per.getName(), value->{
return value+"1";
}));
}
/**
* 指定类型
*/
public static void toTreeSetTest(){
List<PersonModel> data = Data.getData();
TreeSet<PersonModel> collect = data.stream()
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(collect);
}
/**
* 分组
*/
public static void toGroupTest(){
List<PersonModel> data = Data.getData();
Map<Boolean, List<PersonModel>> collect = data.stream()
.collect(Collectors.groupingBy(per -> "男".equals(per.getSex())));
System.out.println(collect);
}
/**
* 分隔
*/
public static void toJoiningTest(){
List<PersonModel> data = Data.getData();
String collect = data.stream()
.map(personModel -> personModel.getName())
.collect(Collectors.joining(",", "{", "}"));
System.out.println(collect);
}
/**
* 自定义
*/
public static void reduce(){
List<String> collect = Stream.of("1", "2", "3").collect(
Collectors.reducing(new ArrayList<String>(), x -> Arrays.asList(x), (y, z) -> {
y.addAll(z);
return y;
}));
System.out.println(collect);
}
#distinct():去除流中重复的元素
#sorted():对流的元素排序
#forEach():对流中的每个元素执行某个操作
#peek():与forEach()方法效果类似,不同的是,该方法会返回一个新的流,而forEach()无返回
#limit():截取流中前面几个元素
#skip():跳过流中前面几个元素
#toArray():将流转换为数组
#reduce():对流中的元素归约操作,将每个元素合起来形成一个新的值
#collect():对流的汇总操作,比如输出成List集合
#anyMatch():匹配流中的元素,类似的操作还有allMatch()和noneMatch()方法
#findFirst():查找第一个元素,类似的还有findAny()方法
#max():求最大值
#min():求最小值
#count():求总数
List
获取某个字段组成新的list
List<String> stringList = objectList.stream().map(Object::getRowkey).collect(Collectors.toList());
排序
List<Student> studentList=Arrays.asList(new Student(1,"ziwen1",10),new Student(2,"aiwen2",18),new Student(3,"biwen3",28));
#自然序列
List<Student> studentList1=studentList.stream().sorted().collect(Collectors.toList());
#逆序
List<Student> studentList2=studentList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
#年龄自然顺序
List<Student> studentList3=studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
#年龄逆序
List<Student> studentList4=studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
#先以速度(降序)、后再价格(升序)
list.sort(Comparator.comparingInt(Computer::getSpeed).reversed().thenComparingInt(Computer::getPrice));
#多条件排序
humans.sort((lhs, rhs) -> {
if (lhs.getName().equals(rhs.getName())) {
return lhs.getAge() - rhs.getAge();
} else {
return lhs.getName().compareTo(rhs.getName());
}
});
#多条件排序并且按照属性删除去重
List<String> ids = new ArrayList<>();
result = result.stream().sorted(Comparator.comparing(ZhihuHotTopic::getLikeCount)
.thenComparing(ZhihuHotTopic::getResponseDate).reversed())
.filter(
v -> {
boolean flag = !ids.contains(v.getTopicId());
ids.add(v.getTopicId());
return flag;
}
).collect(Collectors.toList());
#list<Map<String,Object>> 根据key去重
public static List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>> list, String mapKey) {
List<Map<String, Object>> listMap = new ArrayList<>();
Map<String, Map> msp = new HashMap<>();
for (int i = list.size() - 1; i >= 0; i--) {
Map map = list.get(i);
String id = map.get(mapKey) + "";
map.remove(mapKey);
msp.put(id, map);
}
Set<String> mspKey = msp.keySet();
for (String key : mspKey) {
Map newMap = msp.get(key);
newMap.put(mapKey, key);
listMap.add(newMap);
}
return listMap;
}
#通过其他list当条件过滤
#需要筛选的条件:从stuList中筛选出年龄为21和22的学生
List<Integer> ageList = new ArrayList<Integer>();
ageList.add(21);
ageList.add(22);
//JDK1.8提供了lambda表达式, 可以从stuList中过滤出符合条件的结果。
//定义结果集
List<Student> result = null;
result = stuList.stream()
.filter((Student s) -> ageList.contains(s.getAge()))
.collect(Collectors.toList());
过滤
List<PersonModel> collect1 = data
.stream()
.filter(person -> ("男".equals(person.getSex())&&person.getAge()<20))
.collect(toList());
String str = "1,2,3,4,10,11,9,66,222,12";
List<Integer> list = Stream.of(str.split(","))
.map(Integer::valueOf)
.filter(x-> !Objects.equals(x,3))
.sorted(Comparator.reverseOrder())
.limit(4)
.collect(Collectors.toList());
List<String> words = Arrays.asList("java", "c#", "c++");
List<Integer> wordLength = words.stream().map(String::length).collect(Collectors.toList());
#对list中map元素的key为 publish_time 进行删选,取出日期小于当前时间的
List<Map<String, Object>> listOfResult = this.listOfArtistProductsByArtistId(objectId, 0);
sortList(listOfResult);
listOfResult = listOfResult.stream().filter((e) -> (DateUtil.getDateByFormat(e.get("publish_time") + "", DateUtil.DATE_SHORT).compareTo(new Date()) < 0)).distinct().limit(3).collect(Collectors.toList());
归纳
List<Book> books = Arrays.asList(
new Book("Java编程思想", "Bruce Eckel", "机械工业出版社", 108.00D),
new Book("Java 8实战", "Mario Fusco", "人民邮电出版社", 79.00D),
new Book("MongoDB权威指南(第2版)", "Kristina Chodorow", "人民邮电出版社", 69.00D)
);
#计算所有图书的总价
Optional<Double> totalPrice = books.stream()
.map(Book::getPrice)
.reduce((n, m) -> n + m);
#价格最高的图书
Optional<Book> expensive = books.stream().max(Comparator.comparing(Book::getPrice));
#价格最低的图书
Optional<Book> cheapest = books.stream().min(Comparator.comparing(Book::getPrice));
#计算总数
long count = books.stream().count()
#求和
long count = books.stream().collect(counting());
Long posterSum = list.stream().mapToLong(IfansPosterUser::getPosterNum).sum();
#价格最高的图书
Optional<Book> expensive = books.stream().collect(maxBy(comparing(Book::getPrice)));
#价格最低的图书
Optional<Book> cheapest = books.stream().collect(minBy(comparing(Book::getPrice)));
#求和
private static void test3(List<Person> persons) {
Integer ageSum = persons
.stream()
.reduce(0, (sum, p) -> sum += p.age, (sum1, sum2) -> sum1 + sum2);
System.out.println(ageSum);
}
#计算出现次数
List<String> items = Arrays.asList("Apple", "Apple", "orange",
"Apple", "orange", "banana", "papaya");
Map<String, Long> result = items
.stream()
.collect(Collectors
.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);
{papaya=1, banana=1, orange=2, Apple=3}
#分组
public static List<ListDTO> getBeanDataList(){
List<ListDTO> listDTOS = Arrays.asList(
new ListDTO(1,"a"), new ListDTO(1,"a"),new ListDTO(1,"c"),
new ListDTO(4,"b"),new ListDTO(4,"b"),new ListDTO(4,"c")
);
Map<Integer,List<ListDTO>> listMap = beans.stream().collect(
Collectors.groupingBy(ListDTO::getId));
#求和
Integer collect1 = list.stream().collect(Collectors.summingInt(Integer::intValue));
#按人名统计分数
Map<String, Integer> studentScoreMap2 = new HashMap<>();
studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
studentScore.getStuName(),
studentScore.getScore(),
Integer::sum));
System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
// {"李四":228,"张三":215,"王五":235}
List转Map
List<Person> personList = new ArrayList<>();
personList.add(new Person(1,"aaaa"));
personList.add(new Person(2,"bbbb"));
personList.add(new Person(3,"cccc"));
Map map = personList.stream().collect(Collectors.toMap(p->p.getId(),p->p.getName()));
Map
分组
Map<String, List<Book>> booksGroup = books.stream().collect(groupingBy(Book::getPublisher));
Map<String, List<Book>> booksGroup = books
.stream()
.collect(groupingBy(book -> {
if (book.getPrice() > 0 && book.getPrice() <= 50) {
return "A";
} else if (book.getPrice() > 50 && book.getPrice() <=100) {
return "B";
} else {
return "C";
}
}));
按年龄进行分组:
Map<Integer, List<Person>> personsByAge = persons
.stream()
.collect(Collectors.groupingBy(p -> p.age)); // 以年龄为 key,进行分组
personsByAge
.forEach((age, p) -> System.out.format("age %s: %s\n", age, p));
排序
//排序
Map<String, Long> finalMap = new LinkedHashMap<>();
//Sort a map and add to finalMap
result.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue()
.reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
System.out.println(finalMap);
{Apple=3, orange=2, papaya=1, banana=1}
Array
最大最小
Arrays.stream(numbers).max();
Arrays.stream(numbers).min();
出现次数
Arrays.stream(numbers).filter(number -> number == value).count();
找不同
public static int[] difference(int[] first, int[] second) {
Set<Integer> set = Arrays.stream(second).boxed().collect(Collectors.toSet());
return Arrays.stream(first)
.filter(v -> !set.contains(v))
.toArray();
}
第一次/最后一次出现的下标
public static int indexOf(int[] elements, int el) {
return IntStream.range(0, elements.length)
.filter(idx -> elements[idx] == el)
.findFirst()
.orElse(-1);
}
public static int lastIndexOf(int[] elements, int el) {
return IntStream.iterate(elements.length - 1, i -> i - 1)
.limit(elements.length)
.filter(idx -> elements[idx] == el)
.findFirst()
.orElse(-1);
}
数组转map
public static Map<String, Object> zipObject(String[] props, Object[] values) {
return IntStream.range(0, props.length)
.mapToObj(i -> new SimpleEntry<>(props[i], i < values.length ? values[i] : null))
.collect(
HashMap::new, (m, v) -> m.put(v.getKey(), v.getValue()), HashMap::putAll);
}
平均数
public static double average(int[] arr) {
return IntStream.of(arr)
.average()
.orElseThrow(() -> new IllegalArgumentException("Array is empty"));
}
?Stream.of(new BigDecimal("1.2"), new BigDecimal("3.7"))
.mapToDouble(BigDecimal::doubleValue)
.average()
.ifPresent(System.out::println);
optional
Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
API
#1 ofNullable
String str = "Hello World";
Optional<String> notNullOpt = Optional.of(str);
Optional<String> nullableOpt = Optional.ofNullable(str);
Optional.OfNullable<List>.ifPresent(System.out::println)
#2 orElse
orElse():如果有值就返回,否则返回一个给定的值作为默认值;
orElseGet():与orElse()方法作用类似,区别在于生成默认值的方式不同。该方法接受一个Supplier<? extends T>函数式接口参数,用于生成默认值;
orElseThrow():与前面介绍的get()方法类似,当值为null时调用这两个方法都会抛出NullPointerException异常,区别在于该方法可以指定抛出的异常类型。
String str = "Hello World";
Optional<String> strOpt = Optional.of(str);
String orElseResult = strOpt.orElse("Hello Shanghai");
String orElseGet = strOpt.orElseGet(() -> "Hello Shanghai");
String orElseThrow = strOpt.orElseThrow(
() -> new IllegalArgumentException("Argument ‘str‘ cannot be null or blank."));
#3 filter
Optional<String> optional = Optional.of("[email protected]");
optional = optional.filter(str -> str.contains("164"));
lamda
常用方法
//线程
new Thread(()->System.out.println("线程操作!"));
Runnable newRunnable = () -> {
System.out.println(Thread.currentThread().getName() + ": New Lambda Runnable");
};
new Thread(newRunnable).start();
//筛选隐藏文件
Flie[] hiddenFiles = new File(".").listFiles(File::isHidden);
//比较方法
Comparator<Apple> bycolor2 =(o1,o2)->o1.getColor().compareTo(o2.getColor());
原文地址:https://www.cnblogs.com/gustavo/p/12230004.html
时间: 2024-11-02 12:36:51