“Java8集合转映射”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (建立内容为“1”的新页面) |
Jihongchang(讨论 | 贡献) |
||
第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> |
2022年12月20日 (二) 19:24的版本
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));
}
}