Java常用代码
346字约1分钟
2024-06-25
流操作
排序
数据准备
List<Student> students = new ArrayList<>();
students.add(new Student(18, 88));
students.add(new Student(18, 90));
students.add(new Student(16, 78));
students.add(new Student(15, 98));
students.add(new Student(15, 58));
单字段升序
# 按年龄升序
students.stream()
.sorted(Comparator.comparing(Student::getAge))
.collect(Collectors.toList());
单字段降序
# 按年龄降序排列
students.stream()
.sorted(Comparator.comparing(Student::getAge, Comparator.reverseOrder()))
.collect(Collectors.toList());
# 按年龄降序排列
students.stream()
.sorted(Comparator.comparing(Student::getAge).reversed())
.collect(Collectors.toList());
多字段降序
# 按年龄、成绩降序排列
students.stream()
.sorted(Comparator.comparing(Student::getAge, Comparator.reverseOrder())
.thenComparing(Student::getScore, Comparator.reverseOrder()))
.collect(Collectors.toList());
去重
单字段去重
List<Integer> numbers = Arrays.asList(1, 3, 1, 2, 3);
numbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
对象去重
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* @ClassName:StreamUtils
* @Description:Stream 流工具类
* @Author:MaRui
* @Date:2020/6/20 14:46
* @Version 1.0
**/
public class StreamUtils {
/**
* 去重(去除List中某个字段重复的对象)
* @param keyExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
List<Student> students = new ArrayList<>();
students.add(new Student(18, 88));
students.add(new Student(18, 90));
students.add(new Student(16, 78));
students = students.stream()
.filter(StreamUtils.distinctByKey(Student::getAge))
.collect(Collectors.toList());
随机数
左开右闭,也就是随机4到10的数
RandomUtils.nextInt(4, 11)
类型转换
字符串转换成 boolean 值:Boolean.getBoolean(String name);
// 源码
public final class Boolean implements java.io.Serializable,
Comparable<Boolean>
{
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = parseBoolean(System.getProperty(name));
} catch (IllegalArgumentException | NullPointerException e) {
}
return result;
}
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
}