“Java8集合转映射”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (建立内容为“1”的新页面) |
Jihongchang(讨论 | 贡献) |
||
(未显示同一用户的1个中间版本) | |||
第1行: | 第1行: | ||
− | + | <syntaxhighlight lang="java"> | |
+ | import io.github.jihch.bean.Customer; | ||
+ | import org.junit.Test; | ||
+ | |||
+ | import java.lang.reflect.Field; | ||
+ | import java.util.Arrays; | ||
+ | import java.util.Map; | ||
+ | import java.util.function.Function; | ||
+ | import java.util.stream.Collectors; | ||
+ | |||
+ | /** | ||
+ | * 数组转映射 | ||
+ | */ | ||
+ | public class ArrayToMap { | ||
+ | |||
+ | /** | ||
+ | * 写法1 | ||
+ | */ | ||
+ | @Test | ||
+ | public void test1() { | ||
+ | Map<String, Field> m = Arrays.asList(Customer.class.getDeclaredFields()).stream().collect(Collectors.toMap(Field::getName, Function.identity())); | ||
+ | m.forEach((k, v) -> System.out.printf("k:%s, v:%s\n", k, v)); | ||
+ | } | ||
+ | |||
+ | @Test | ||
+ | public void test2(){ | ||
+ | Map<String, Field> m = Arrays.asList(Customer.class.getDeclaredFields()).stream().collect(Collectors.toMap(t->t.getName(), t->t)); | ||
+ | m.forEach((k, v) -> System.out.printf("k:%s, v:%s\n", k, v)); | ||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | k:name, v:private java.lang.String io.github.jihch.bean.Customer.name | ||
+ | k:birth, v:private java.sql.Date io.github.jihch.bean.Customer.birth | ||
+ | k:id, v:private int io.github.jihch.bean.Customer.id | ||
+ | k:email, v:private java.lang.String io.github.jihch.bean.Customer.email | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | https://github.com/jihch/java8/blob/main/src/main/java/io/github/jihch/ArrayToMap.java |
2022年12月20日 (二) 19:43的最新版本
import io.github.jihch.bean.Customer;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 数组转映射
*/
public class ArrayToMap {
/**
* 写法1
*/
@Test
public void test1() {
Map<String, Field> m = Arrays.asList(Customer.class.getDeclaredFields()).stream().collect(Collectors.toMap(Field::getName, Function.identity()));
m.forEach((k, v) -> System.out.printf("k:%s, v:%s\n", k, v));
}
@Test
public void test2(){
Map<String, Field> m = Arrays.asList(Customer.class.getDeclaredFields()).stream().collect(Collectors.toMap(t->t.getName(), t->t));
m.forEach((k, v) -> System.out.printf("k:%s, v:%s\n", k, v));
}
}
k:name, v:private java.lang.String io.github.jihch.bean.Customer.name
k:birth, v:private java.sql.Date io.github.jihch.bean.Customer.birth
k:id, v:private int io.github.jihch.bean.Customer.id
k:email, v:private java.lang.String io.github.jihch.bean.Customer.email
https://github.com/jihch/java8/blob/main/src/main/java/io/github/jihch/ArrayToMap.java