Lambda 表达式练习
目录
sorted() 四种排序
List 转 Map
map 映射
对象中 String 类型属性为空的字段赋值为 null
BiConsumer,>
T reduce(T identity, BinaryOperator accumulator)
allMatch(Predicate p)
groupingBy(Function f)
flatMap(Function f)
Optional.ofNullable(T t) 和 T orElse(T other)
先来写个基本类
public class LambdaTest {@Dataclass Student {private Integer id;private String name;private Integer age;public Student(Integer id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}}public List<Student> getStudents() {List<Student> list = new ArrayList<>();list.add(new Student(100, "小明", 10));list.add(new Student(101, "小红", 11));list.add(new Student(102, "小李", 12));list.add(new Student(103, "小王", 13));list.add(new Student(104, "小张", 14));list.add(new Student(105, "小五", 15));list.add(new Student(106, "小华", 16));return list;}
}
sorted()
四种排序
@Test
public void sortedTest() {List<Student> students = this.getStudents();//正序:常规写法List<Student> collect = students.stream().sorted((a1, a2) -> Integer.compare(a1.getAge(), a2.getAge())).collect(Collectors.toList());collect.forEach(System.out::println);System.out.println();//正序:lambda 简写List<Student> collectComparator = students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());collectComparator.forEach(System.out::println);System.out.println();//倒序:常规写法List<Student> collectReversed = students.stream().sorted((a1, a2) -> Integer.compare(a2.getAge(), a1.getAge())).collect(Collectors.toList());collectReversed.forEach(System.out::println);System.out.println();//正序:lambda 简写List<Student> collectComparatorReversed = students.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());collectComparatorReversed.forEach(System.out::println);
}
List
转 Map
@Test
public void listToMapTest() {List<Student> students = this.getStudents();Map<Integer, Student> collect = students.stream().collect(Collectors.toMap(Student::getId, s -> s, (s1, s2) -> s1));collect.keySet().forEach(key -> System.out.println(String.format("key:%s,value:%s", key, collect.get(key))));
}
map
映射
@Testpublic void mapTest() {List<Student> students = this.getStudents();
// List<Student> students = Lists.newArrayList(new Student(null, "小炎姬", 5));Integer id = students.stream().map(Student::getId).max(Integer::compareTo).orElse(0);System.out.println(id);}
对象中 String
类型属性为空的字段赋值为 null
public static <T> void stringEmptyToNull(T t) {Class<?> clazz = t.getClass();Field[] fields = clazz.getDeclaredFields();Arrays.stream(fields).filter(f -> f.getType() == String.class).filter(f -> {try {f.setAccessible(true);String value = (String) f.get(t);return StringUtils.isEmpty(value);} catch (Exception ignore) {return false;}}).forEach(field -> {try {field.setAccessible(true);field.set(t, null);} catch (Exception ignore) {}});
}
BiConsumer<T, U>
<!-- lombok -->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version>
</dependency><!-- guava -->
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>28.2-jre</version>
</dependency>
/*** @author vincent*/
public class LambdaTest {@Dataprivate static class Student {private Integer id;private String name;private Integer age;private Integer interestType;private List<Hobby> hobbies;private List<Fancy> fancies;private Subject subject;private Student(Integer id, String name, Integer age, Integer interestType, List<Hobby> hobbies, List<Fancy> fancies, Subject subject) {this.id = id;this.name = name;this.age = age;this.interestType = interestType;this.hobbies = hobbies;this.fancies = fancies;this.subject = subject;}}enum InterestType {HOBBY(1, "兴趣"),FANCY(2, "喜好");private Integer code;private String message;InterestType(Integer code, String message) {this.code = code;this.message = message;}public Integer getCode() {return code;}public static InterestType getInterestTypeByCode(int code) {return Arrays.stream(InterestType.values()).filter(interestType -> interestType.getCode() == code).findFirst().orElse(null);}}@Dataprivate static class Hobby {private String basketball;private String running;private String drinking;private Hobby(String basketball, String running, String drinking) {this.basketball = basketball;this.running = running;this.drinking = drinking;}}@Dataprivate static class Fancy {private String dance;private String takePhotos;private String meetGirls;private Fancy(String dance, String takePhotos, String meetGirls) {this.dance = dance;this.takePhotos = takePhotos;this.meetGirls = meetGirls;}}@Dataprivate static class Subject {private String english;private String chinese;private String mathematics;private Subject(String english, String chinese, String mathematics) {this.english = english;this.chinese = chinese;this.mathematics = mathematics;}}private List<Student> getStudent() {List<Student> list = Lists.newArrayList();list.add(new Student(100, "小明", 10, 1,Lists.newArrayList(new Hobby("篮球", "跑步", "喝酒"),new Hobby("篮球_1", "跑步_1", "喝酒_1"),new Hobby("篮球_2", "跑步_2", "喝酒_2"),new Hobby("篮球_3", "跑步_3", "喝酒_3")),Lists.newArrayList(new Fancy("街舞", "摄影", "泡妞"),new Fancy("街舞_1", "摄影_1", "泡妞_1"),new Fancy("街舞_2", "摄影_2", "泡妞_2"),new Fancy("街舞_3", "摄影_3", "泡妞_3")),new Subject("英语", "语文", "数学")));list.add(new Student(200, "小红", 10, 2,Lists.newArrayList(new Hobby("篮球", "跑步", "喝酒"),new Hobby("篮球_1", "跑步_1", "喝酒_1"),new Hobby("篮球_2", "跑步_2", "喝酒_2"),new Hobby("篮球_3", "跑步_3", "喝酒_3")),Lists.newArrayList(new Fancy("街舞", "摄影", "泡妞"),new Fancy("街舞_1", "摄影_1", "泡妞_1"),new Fancy("街舞_2", "摄影_2", "泡妞_2"),new Fancy("街舞_3", "摄影_3", "泡妞_3")),new Subject("英语", "语文", "数学")));return list;}@Dataprivate static class Person {private Integer pid;private String pname;private Integer page;private String interest;private String subject;}private final static BiConsumer<Person, Student> HOBBY = (person, student) -> {Optional.ofNullable(student.getHobbies()).flatMap(hobbies -> hobbies.stream().findFirst()).ifPresent(hobby -> person.setInterest(hobby.getDrinking()));Optional.ofNullable(student.subject).ifPresent(subject -> person.setSubject(subject.getEnglish()));};private final static BiConsumer<Person, Student> FANCY = (person, student) -> {Optional.ofNullable(student.getFancies()).flatMap(fancies -> fancies.stream().findFirst()).ifPresent(fancy -> person.setInterest(fancy.getDance()));Optional.ofNullable(student.subject).ifPresent(subject -> person.setSubject(subject.getMathematics()));};private final static ImmutableMap<InterestType, BiConsumer<Person, Student>> OF = ImmutableMap.of(InterestType.HOBBY, HOBBY,InterestType.FANCY, FANCY);/*** BiConsumer<T, U> 实例*/@Testpublic void t() {List<Student> studentList = getStudent();List<Object> collect = studentList.stream().map(student -> {Person person = new Person();Optional.ofNullable(student).ifPresent(stu -> {person.setPid(stu.getId());person.setPname(stu.getName());person.setPage(stu.getAge());Integer interestType = student.getInterestType();InterestType interestTypeByCode = InterestType.getInterestTypeByCode(interestType);person.setInterest(interestTypeByCode.message);OF.get(interestTypeByCode).accept(person, student);});return person;}).collect(Collectors.toList());System.out.println(collect);}
}
T reduce(T identity, BinaryOperator<T> accumulator)
<!-- commons-lang3 -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version>
</dependency>
/*** @author qfxl*/
public class LambdaTest {@Dataprivate static class trip {private String departure;private String destination;private trip(String departure, String destination) {this.departure = departure;this.destination = destination;}}/*** reduce 规则:* 例子:1.上海 -> 北京* 2.北京 -> 上海* 3.天津 -> 西安* 4.拉萨 -> 灵芝* 5.灵芝 -> 兰州* 6.兰州 -> 西宁* 展示效果:上海-北京-上海,天津-西安,拉萨-灵芝-兰州-西宁*/private static final BinaryOperator<String> ACCUMULATOR = (v1, v2) -> {if (StringUtils.isEmpty(v1)) {return v2;}String[] item = StringUtils.split(v1, ",");String[] lastOfItem = StringUtils.split(item[item.length - 1], "-");String lastElement = lastOfItem[lastOfItem.length - 1];String[] nextItem = StringUtils.split(v2, "-");String startElement = nextItem[0];if (StringUtils.equals(lastElement, startElement)) {return v1 + "-" + nextItem[nextItem.length - 1];}return v1 + "," + v2;};@Testpublic void t2() {List<trip> list = Lists.newArrayList(new trip("上海", "北京"),new trip("北京", "上海"),new trip("天津", "西安"),new trip("拉萨", "灵芝"),new trip("灵芝", "兰州"),new trip("兰州", "西宁"));//[上海-北京-上海,天津-西安,拉萨-灵芝-兰州-西宁]String reduce = list.stream().map(t -> String.format("%s-%s", t.getDeparture(), t.getDestination())).reduce("", ACCUMULATOR);System.out.println(reduce);}
}
allMatch(Predicate p)
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY__MM__DD = "yyyy/MM/dd";
public static final String YYYY__MM__DD_HH_MM = "yyyy/MM/dd HH:mm";
public static final String YYYY__MM__DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";@Test
public void t3() {@Dataclass DateValidate {private String date;private String dateFormat;public DateValidate(String date, String dateFormat) {this.date = date;this.dateFormat = dateFormat;}}List<DateValidate> list = Lists.newArrayList(new DateValidate("202086", YYYYMMDD),new DateValidate("2020086", YYYYMMDD),new DateValidate("2020806", YYYYMMDD),new DateValidate("20200806", YYYYMMDD),new DateValidate("20200806 19", null),new DateValidate("20200806 19:00", null),new DateValidate("20200806 19:00:00", null),new DateValidate("2020-8-06", YYYY_MM_DD),new DateValidate("2020-08-6", YYYY_MM_DD),new DateValidate("2020-08-06", YYYY_MM_DD),new DateValidate("2020-08-06 19", null),new DateValidate("2020-08-06 19:00", YYYY_MM_DD_HH_MM),new DateValidate("2020-08-06 19:00:00", YYYY_MM_DD_HH_MM_SS),new DateValidate("2020/8/06", YYYY__MM__DD),new DateValidate("2020/08/6", YYYY__MM__DD),new DateValidate("2020/08/06", YYYY__MM__DD),new DateValidate("2020/08/06 19", null),new DateValidate("2020/08/06 19:00", YYYY__MM__DD_HH_MM),new DateValidate("2020/08/06 19:00:00", YYYY__MM__DD_HH_MM_SS));list.forEach(item -> {boolean matchDateTime = matchDateTime(item.getDate());System.out.println(item.getDate() + " (" + item.getDateFormat() + "):matchDateTime -> " + matchDateTime);});
}/*** 时间校验* @param dateTime* @return*/
public static boolean matchDateTime(String dateTime) {if (StringUtils.isEmpty(dateTime)) {return false;}String[] dt = dateTime.split("\\s+");if (dt.length == 1) {return dateMatch(dt[0], "/") || dateMatch(dt[0], "-");} else {String date = dt[0];String time = dt[1];return (dateMatch(date, "/") || dateMatch(date, "-")) && timeMatch(time, ":");}
}private static boolean timeMatch(String s, String split) {if (StringUtils.isEmpty(s)) {return true;}s = StringUtils.trim(s);String[] time = StringUtils.split(s, split);boolean isNumber = Arrays.stream(time).anyMatch(StringUtils::isNumeric);if (!isNumber) {return false;}if (time.length != 3) {return false;}if (time[0].length() > 2 || Integer.parseInt(time[0]) > 24) {return false;}if (time[1].length() > 2 || Integer.parseInt(time[1]) > 60) {return false;}if (time[2].length() > 2 || Integer.parseInt(time[2]) > 60) {return false;}return true;
}private static boolean dateMatch(String s, String spl) {if (StringUtils.isEmpty(s)) {return false;}s = StringUtils.trim(s);String[] date = StringUtils.split(s, spl);boolean isNumber = Arrays.stream(date).anyMatch(StringUtils::isNumeric);if (!isNumber) {return false;}if (date.length != 3) {return false;}if (date[0].length() != 4) {return false;}if (Integer.parseInt(date[1]) > 12) {return false;}if (Integer.parseInt(date[2]) > 31) {return false;}return true;
}
显示结果
202086 (yyyyMMdd):matchDateTime -> false
2020086 (yyyyMMdd):matchDateTime -> false
2020806 (yyyyMMdd):matchDateTime -> false
20200806 (yyyyMMdd):matchDateTime -> false
20200806 19 (null):matchDateTime -> false
20200806 19:00 (null):matchDateTime -> false
20200806 19:00:00 (null):matchDateTime -> false
2020-8-06 (yyyy-MM-dd):matchDateTime -> true
2020-08-6 (yyyy-MM-dd):matchDateTime -> true
2020-08-06 (yyyy-MM-dd):matchDateTime -> true
2020-08-06 19 (null):matchDateTime -> false
2020-08-06 19:00 (yyyy-MM-dd HH:mm):matchDateTime -> false
2020-08-06 19:00:00 (yyyy-MM-dd HH:mm:ss):matchDateTime -> true
2020/8/06 (yyyy/MM/dd):matchDateTime -> true
2020/08/6 (yyyy/MM/dd):matchDateTime -> true
2020/08/06 (yyyy/MM/dd):matchDateTime -> true
2020/08/06 19 (null):matchDateTime -> false
2020/08/06 19:00 (yyyy/MM/dd HH:mm):matchDateTime -> false
2020/08/06 19:00:00 (yyyy/MM/dd HH:mm:ss):matchDateTime -> true
groupingBy(Function f)
@Test
public void t5() {@Dataclass Stu {private Integer id;private String name;private Long money;public Stu(Integer id, String name, Long money) {this.id = id;this.name = name;this.money = money;}}List<Stu> list = Lists.newArrayList(new Stu(1, "小明", 100L),new Stu(1, "小红", 200L),new Stu(2, "小黄", 200L),new Stu(2, "小紫", 200L));Map<Integer, List<Stu>> collect = list.stream().collect(Collectors.groupingBy(Stu::getId));System.out.println(JSON.toJSONString(collect, SerializerFeature.PrettyFormat));
}
显示结果
{1:[{"id":1,"money":100,"name":"小明"},{"id":1,"money":200,"name":"小红"}],2:[{"id":2,"money":200,"name":"小黄"},{"id":2,"money":200,"name":"小紫"}]
}
flatMap(Function f)
@Data
private static class TravelInfo {private String trip;private String hotelName;private List<Order> orders;public TravelInfo(String trip, String hotelName, List<Order> orders) {this.trip = trip;this.hotelName = hotelName;this.orders = orders;}
}@Data
private static class Order {private Long orderId;private List<Travellers> travellers;public Order(Long orderId, List<Travellers> travellers) {this.orderId = orderId;this.travellers = travellers;}
}@Data
private static class Travellers {private String userName;private String email;public Travellers() {}public Travellers(String userName, String email) {this.userName = userName;this.email = email;}
}/*** flatMap(Function f):扁平化*/
@Test
public void t5() {TravelInfo travelInfo = new TravelInfo("三人行", "天上人间",Lists.newArrayList(new Order(123456789L, Lists.newArrayList(new Travellers("zhangSanFirst", "zhangSanFirst@qq.com"),new Travellers("zhangSanSecond", "zhangSanSecond@qq.com"))),new Order(987654321L, Lists.newArrayList(new Travellers("liSiFirst", "zhangSanFirst@qq.com"),new Travellers("liSiSecond", "zhangSanSecond@qq.com"))),new Order(987654322L, Lists.newArrayList(new Travellers("wangWu", "wangWu@qq.com"))),new Order(987654323L, Lists.newArrayList()),new Order(987654323L, null)));System.out.println(JSON.toJSONString(travelInfo, SerializerFeature.PrettyFormat));System.out.println();List<String> email = travelInfo.getOrders().stream().filter(Objects::nonNull).map(Order::getTravellers).filter(CollectionUtils::isNotEmpty).flatMap(Collection::stream).filter(Objects::nonNull).map(Travellers::getEmail).collect(Collectors.toList());System.out.println(email);
}
显示结果
{"hotelName":"天上人间","orders":[{"orderId":123456789,"travellers":[{"email":"zhangSanFirst@qq.com","userName":"zhangSanFirst"},{"email":"zhangSanSecond@qq.com","userName":"zhangSanSecond"}]},{"orderId":987654321,"travellers":[{"email":"zhangSanFirst@qq.com","userName":"liSiFirst"},{"email":"zhangSanSecond@qq.com","userName":"liSiSecond"}]},{"orderId":987654322,"travellers":[{"email":"wangWu@qq.com","userName":"wangWu"}]},{"orderId":987654323,"travellers":[]},{"orderId":987654323}],"trip":"三人行"
}[zhangSanFirst@qq.com, zhangSanSecond@qq.com, zhangSanFirst@qq.com, zhangSanSecond@qq.com, wangWu@qq.com]
Optional.ofNullable(T t)
和 T orElse(T other)
@Data
private class PaymentDto {private Long id;private String liqAccountName;/*** 来款业务:COMPANY-企业来款;OFFLINE-订单线下收款*/private String paymentMode;private List<ClaimDto> claimDto;private List<OrderClaimDto> orderClaimDto;public PaymentDto(Long id, String liqAccountName, String paymentMode, List<ClaimDto> claimDto, List<OrderClaimDto> orderClaimDto) {this.id = id;this.liqAccountName = liqAccountName;this.paymentMode = paymentMode;this.claimDto = claimDto;this.orderClaimDto = orderClaimDto;}
}@Data
private static class ClaimDto {private Long paymentId;private String partnerName;private Integer amount;public ClaimDto(Long paymentId, String partnerName, Integer amount) {this.paymentId = paymentId;this.partnerName = partnerName;this.amount = amount;}
}@Data
private static class OrderClaimDto {private Long paymentId;private Integer amount;public OrderClaimDto(Long paymentId, Integer amount) {this.paymentId = paymentId;this.amount = amount;}
}@Data
private static class PaymentApiDto {private Long id;private String liqAccountName;private String paymentMode;private Long paymentId;private String partnerName;private Integer amount;
}private List<PaymentDto> getPaymentDto() {List<PaymentDto> list = Lists.newArrayList();list.add(new PaymentDto(123456789L, "收款账户_COMPANY", "COMPANY",Lists.newArrayList(new ClaimDto(123456789L, "企业名称1", 999),new ClaimDto(123456789L, "企业名称2", 888),new ClaimDto(123456789L, "企业名称3", 777)),Lists.newArrayList(new OrderClaimDto(123456789L, 666),new OrderClaimDto(123456789L, 555))));list.add(new PaymentDto(987654321L, "收款账户_OFFLINE", "OFFLINE",Lists.newArrayList(new ClaimDto(987654321L, "企业名称1", 999),new ClaimDto(987654321L, "企业名称2", 888)),Lists.newArrayList(new OrderClaimDto(987654321L, 666),new OrderClaimDto(987654321L, 555))));list.add(new PaymentDto(888888888L, "收款账户", null, null, null));return list;
}/*** Optional.ofNullable(T t) 和 T orElse(T other)*/
@Test
public void t6() {List<PaymentDto> paymentDtos = getPaymentDto();paymentDtos.forEach(System.out::println);System.out.println();/*** 根据 paymentMode 把 claimDto、orderClaimDto 集合数据查分为单条数据*/List<PaymentApiDto> collect = paymentDtos.stream().map(paymentDto -> {PaymentApiDto apiDto = new PaymentApiDto();apiDto.setId(paymentDto.getId());apiDto.setLiqAccountName(paymentDto.getLiqAccountName());apiDto.setPaymentMode(paymentDto.getPaymentMode());ImmutableList<PaymentApiDto> defaultList = ImmutableList.of(apiDto);if (StringUtils.equals(paymentDto.getPaymentMode(), "COMPANY")) {return Optional.ofNullable(paymentDto.getClaimDto()).map(claimDtos -> claimDtos.stream().map(claimDto -> {PaymentApiDto paymentApiDto = new PaymentApiDto();paymentApiDto.setId(paymentDto.getId());paymentApiDto.setLiqAccountName(paymentDto.getLiqAccountName());paymentApiDto.setPaymentMode(paymentDto.getPaymentMode());paymentApiDto.setPaymentId(claimDto.getPaymentId());paymentApiDto.setPartnerName(claimDto.getPartnerName());paymentApiDto.setAmount(claimDto.getAmount());return paymentApiDto;}).collect(Collectors.toList())).orElse(defaultList);}if (StringUtils.equals(paymentDto.getPaymentMode(), "OFFLINE")) {return Optional.ofNullable(paymentDto.getOrderClaimDto()).map(orderClaimDtos -> orderClaimDtos.stream().map(orderClaimDto -> {PaymentApiDto paymentApiDto = new PaymentApiDto();paymentApiDto.setId(paymentDto.getId());paymentApiDto.setLiqAccountName(paymentDto.getLiqAccountName());paymentApiDto.setPaymentMode(paymentDto.getPaymentMode());paymentApiDto.setAmount(orderClaimDto.getAmount());return paymentApiDto;}).collect(Collectors.toList())).orElse(defaultList);}return defaultList;}).flatMap(Collection::stream).collect(Collectors.toList());collect.forEach(System.out::println);
}
显示结果
LambdaTest.PaymentDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, claimDto=[LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称1, amount=999), LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称2, amount=888), LambdaTest.ClaimDto(paymentId=123456789, partnerName=企业名称3, amount=777)], orderClaimDto=[LambdaTest.OrderClaimDto(paymentId=123456789, amount=666), LambdaTest.OrderClaimDto(paymentId=123456789, amount=555)])
LambdaTest.PaymentDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, claimDto=[LambdaTest.ClaimDto(paymentId=987654321, partnerName=企业名称1, amount=999), LambdaTest.ClaimDto(paymentId=987654321, partnerName=企业名称2, amount=888)], orderClaimDto=[LambdaTest.OrderClaimDto(paymentId=987654321, amount=666), LambdaTest.OrderClaimDto(paymentId=987654321, amount=555)])
LambdaTest.PaymentDto(id=888888888, liqAccountName=收款账户, paymentMode=null, claimDto=null, orderClaimDto=null)LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称1, amount=999)
LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称2, amount=888)
LambdaTest.PaymentApiDto(id=123456789, liqAccountName=收款账户_COMPANY, paymentMode=COMPANY, paymentId=123456789, partnerName=企业名称3, amount=777)
LambdaTest.PaymentApiDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, paymentId=null, partnerName=null, amount=666)
LambdaTest.PaymentApiDto(id=987654321, liqAccountName=收款账户_OFFLINE, paymentMode=OFFLINE, paymentId=null, partnerName=null, amount=555)
LambdaTest.PaymentApiDto(id=888888888, liqAccountName=收款账户, paymentMode=null, paymentId=null, partnerName=null, amount=null)
相关文章:
Lambda 表达式练习
目录 sorted() 四种排序 List 转 Map map 映射 对象中 String 类型属性为空的字段赋值为 null BiConsumer,> T reduce(T identity, BinaryOperator accumulator) allMatch(Predicate p) groupingBy(Function f) flatMap(Function f) Optional.ofNullable(T t) 和 …...
JavaScript第七讲:数组,及练习题
目录 今天话不多说直接进入正题! 1. 创建数组对象 2. 数组长度 3. 遍历一个数组 4. 连接数组 5. 通过指定分隔符,返回一个数组的字符串表达 6. 分别在最后的位置插入数据和获取数据(获取后删除) 7. 分别在最开始的位置插入数据和获取数据(获取后删…...
从docker镜像反推Dockerfile
在项目运维的过程中,偶尔会遇到某个docker image打包时候的Dockerfile版本管理不善无法与image对应的问题,抑或需要分析某个三方docker image的构建过程,这时,就希望能够通过image反推构建时的instruction. 想实现这个过程可以使…...

车载软件架构 - AUTOSAR 的信息安全框架
车载软件架构 - AUTOSAR 的信息安全架构 我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 屏蔽力是信息过载时代一个人的特殊竞争力,任何消耗…...
欧洲版“OpenAI”——Mistral 举办的 AI 大模型马拉松
近期,法国的 Mistral AI 举办了一场别开生面的 AI 大模型马拉松。要知道,Mistral 可是法国对 OpenAI 的有力回应,而且其技术还是完全开源的呢!这场在巴黎举行的黑客马拉松,规模空前盛大,竟然有超过 1000 名…...

Java | Leetcode Java题解之第128题最长连续序列
题目: 题解: class Solution {public int longestConsecutive(int[] nums) {Set<Integer> num_set new HashSet<Integer>();for (int num : nums) {num_set.add(num);}int longestStreak 0;for (int num : num_set) {if (!num_set.contai…...

C++的List
List的使用 构造 与vector的区别 与vector的区别在于不支持 [ ] 由于链表的物理结构不连续,所以只能用迭代器访问 vector可以排序,list不能排序(因为快排的底层需要随机迭代器,而链表是双向迭代器) (算法库里的排序不支持)(需要单独的排序) list存在vector不支持的功能 链…...

网易有道QAnything使用CPU模式和openAI接口安装部署
网易有道QAnything可以使用本地部署大模型(官网例子为qwen)也可以使用大模型接口(OPENAI或者其他大模型AI接口 )的方式,使用在线大模型API接口好处就是不需要太高的硬件配置。 本机环境windows11 首先安装WSL环境, 安装方法参考https://zhuan…...

量子加速超级计算简介
本文转载自:量子加速超级计算简介(2024年 3月 13日) By Mark Wolf https://developer.nvidia.cn/zh-cn/blog/an-introduction-to-quantum-accelerated-supercomputing/ 文章目录 一、概述二、量子计算机的构建块:QPU 和量子位三、量子计算硬件和算法四、…...
Unity3D 基于YooAssets的资源管理详解
前言 Unity3D 是一款非常流行的游戏开发引擎,它提供了丰富的功能和工具来帮助开发者快速创建高质量的游戏和应用程序。其中,资源管理是游戏开发中非常重要的一部分,它涉及到如何有效地加载、管理和释放游戏中的各种资源,如模型、…...
Linux 自动化升级Jar程序,指定Jar程序版本进行部署脚本
文章目录 一、环境准备二、脚本1. 自动化升级Jar程序2. 指定Jar程序版本进行部署总结一、环境准备 本文在 CentOS 7.9 环境演示,以springboot为例,打包后生成文件名加上版本号,如下打包之后为strategy-api-0.3.2.jar: pom.xml<?xml version="1.0" encoding=&…...
python练习五
Title1:请实现一个装饰器,每次调用函数时,将函数名字以及调用此函数的时间点写入文件中 代码: import time time time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 获取当前的时间戳 # 定义一个有参装饰器来实…...

YOLOv1深入解析与实战:目标检测算法原理
参考: https://zhuanlan.zhihu.com/p/667046384 https://blog.csdn.net/weixin_41424926/article/details/105383064 https://arxiv.org/pdf/1506.02640 1. 算法介绍 学习目标检测算法,yolov1是必看内容,不同于生成模型,没有特别…...

Apache Calcite - 自定义标量函数
前言 上一篇文章中我们介绍了calcite中内置函数的使用。实际需求中会遇到一些场景标准内置函数无法满足需求,这时候就需要用到自定义函数。在 Apache Calcite 中添加自定义函数,以便在 SQL 查询中使用自定义的逻辑。这对于执行特定的数据处理或分析任务…...

STM32作业实现(四)光敏传感器
目录 STM32作业设计 STM32作业实现(一)串口通信 STM32作业实现(二)串口控制led STM32作业实现(三)串口控制有源蜂鸣器 STM32作业实现(四)光敏传感器 STM32作业实现(五)温湿度传感器dht11 STM32作业实现(六)闪存保存数据 STM32作业实现(七)OLED显示数据 STM32作业实现(八)触摸按…...

HTML+CSS 文本动画卡片
效果演示 实现了一个图片叠加文本动画效果的卡片(Card)布局。当鼠标悬停在卡片上时,卡片上的图片会变为半透明,同时显示隐藏在图片上的文本内容,并且文本内容有一个从左到右的渐显动画效果,伴随着一个白色渐…...
MongoDB CRUD操作: 在本地实例进行文本搜索查询
MongoDB CRUD操作: 在本地实例进行文本搜索查询 文章目录 MongoDB CRUD操作: 在本地实例进行文本搜索查询举例创建集合创建文本索引精准搜索排除短语结果排序 在本地实例运行文本搜索查询前,必须先在集合上建立文本索引。MongoDB提供文本索引…...
文档智能开源软件
文档智能介绍: 文档智能通常指的是利用人工智能技术来处理和分析文档内容,以实现自动化、智能化的文档管理。文档智能的应用领域非常广泛,包括但不限于: 1. **文档识别**:使用OCR(光学字符识别࿰…...

[C][可变参数列表]详细讲解
目录 1.宏含义及使用2.宏原理分析1.原理2.宏理解 1.宏含义及使用 依赖库stdarg.hva_list 其实就是char*类型,方便后续按照字节进行指针移动 va_start(arg, num) 使arg指向可变参数部分(num后面) va_arg(arg, int) 先让arg指向下个元素,然后使用相对位置…...

54. 螺旋矩阵【rust题解】
题目 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 示例 示例 1 输入:matrix [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5] 示例 2 输入:matrix [[1,2,3,4],[5,6,…...

idea大量爆红问题解决
问题描述 在学习和工作中,idea是程序员不可缺少的一个工具,但是突然在有些时候就会出现大量爆红的问题,发现无法跳转,无论是关机重启或者是替换root都无法解决 就是如上所展示的问题,但是程序依然可以启动。 问题解决…...
SciencePlots——绘制论文中的图片
文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了:一行…...
解锁数据库简洁之道:FastAPI与SQLModel实战指南
在构建现代Web应用程序时,与数据库的交互无疑是核心环节。虽然传统的数据库操作方式(如直接编写SQL语句与psycopg2交互)赋予了我们精细的控制权,但在面对日益复杂的业务逻辑和快速迭代的需求时,这种方式的开发效率和可…...
基础测试工具使用经验
背景 vtune,perf, nsight system等基础测试工具,都是用过的,但是没有记录,都逐渐忘了。所以写这篇博客总结记录一下,只要以后发现新的用法,就记得来编辑补充一下 perf 比较基础的用法: 先改这…...

基于SpringBoot在线拍卖系统的设计和实现
摘 要 随着社会的发展,社会的各行各业都在利用信息化时代的优势。计算机的优势和普及使得各种信息系统的开发成为必需。 在线拍卖系统,主要的模块包括管理员;首页、个人中心、用户管理、商品类型管理、拍卖商品管理、历史竞拍管理、竞拍订单…...

【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)
前言: 双亲委派机制对于面试这块来说非常重要,在实际开发中也是经常遇见需要打破双亲委派的需求,今天我们一起来探索一下什么是双亲委派机制,在此之前我们先介绍一下类的加载器。 目录 编辑 前言: 类加载器 1. …...

永磁同步电机无速度算法--基于卡尔曼滤波器的滑模观测器
一、原理介绍 传统滑模观测器采用如下结构: 传统SMO中LPF会带来相位延迟和幅值衰减,并且需要额外的相位补偿。 采用扩展卡尔曼滤波器代替常用低通滤波器(LPF),可以去除高次谐波,并且不用相位补偿就可以获得一个误差较小的转子位…...

UE5 音效系统
一.音效管理 音乐一般都是WAV,创建一个背景音乐类SoudClass,一个音效类SoundClass。所有的音乐都分为这两个类。再创建一个总音乐类,将上述两个作为它的子类。 接着我们创建一个音乐混合类SoundMix,将上述三个类翻入其中,通过它管理每个音乐…...
手动给中文分词和 直接用神经网络RNN做有什么区别
手动分词和基于神经网络(如 RNN)的自动分词在原理、实现方式和效果上有显著差异,以下是核心对比: 1. 实现原理对比 对比维度手动分词(规则 / 词典驱动)神经网络 RNN 分词(数据驱动)…...
大模型真的像人一样“思考”和“理解”吗?
Yann LeCun 新研究的核心探讨:大语言模型(LLM)的“理解”和“思考”方式与人类认知的根本差异。 核心问题:大模型真的像人一样“思考”和“理解”吗? 人类的思考方式: 你的大脑是个超级整理师。面对海量信…...