一、遍历map集合的4种方式
public static void show(Map<String,Integer> map){
//第一种:获取map键值
for(String in : map.keySet()){
Integer z = map.get(in);
System.out.println(in+"=="+z);
}
//第二种:获取map键值【推荐使用这种】
for(Map.Entry<String,Integer> m : map.entrySet()){
System.out.println(m.getKey()+"=="+m.getValue());
}
//第三种:获取map值
for(Integer i : map.values()){
System.out.println(i+"==");
}
//第四种:获取map键值
Iterator<Map.Entry<Integer, String>> it1 = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it1.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//【拓展】
Iterator<Employee> it = es.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
二、比较大小
public void test2(){
Collections.sort(es,(q1,q2)->{
if(q1.getAge()==q2.getAge()){
return q2.getName().compareTo(q1.getName());//小.compareTo(大);
}else {
return Integer.compare(q1.getAge(),q2.getAge());
}
});
es.forEach(System.out::println);
}
三、四大核心函数式接口
@Test
public void test2(){
System.out.println(filter("\t\t\t你好",(s)->s.length()>2));
System.out.println(show("asdf",(z)->z.toUpperCase()));
System.out.println(getNum(5,()->(int)(Math.random()*100)));
consume(125,(z)-> System.out.println(z));
}
public static List<Integer> getNum(Integer num, Supplier<Integer> s){
List<Integer> ls = new ArrayList<>();
for (Integer i = 0; i < num; i++) {
ls.add(s.get());
}
return ls;
}
public static String show(String s , Function<String,String> m){
return m.apply(s);
}
public static void consume(Integer s , Consumer<Integer> m){
m.accept(s);
}
public static List<String> filter(String s, Predicate<String> p){
List<String> ls = new ArrayList<>();
if(p.test(s)){
ls.add(s);
}
return ls;
}
四、方法引用
@Test
public void test1(){
Consumer<String> z= System.out::println;
z.accept("zzzz");
Employee e= new Employee(1,"2",212);
Supplier<String> s = ()->e.getName();
System.out.println(s.get());
Supplier<Integer> z0 = e::getAge;
System.out.println(z0.get());
Comparator<Integer> con = Integer::compare;
System.out.println(con.compare(1,2));
// lamda体的参数列表和返回值类型,与函数式接口中的返回值,保持一致。
Supplier<Employee> s1 = ()->new Employee(1,"1",1);
System.out.println(s1.get());
Supplier<Employee> z1 = Employee::new;
System.out.println(z1.get());
Function<Integer,Employee> c= Employee::new;
Employee x= c.apply(1);
System.out.println(x);
BiFunction<Integer,String,Employee> b = Employee::new;
Employee a = b.apply(1,"1");
System.out.println(a);
Function<Integer,String[]> f = String[]::new;
String[] a1 = f.apply(20);
System.out.println(a1.length);
}