java8之方法錦集
阿新 • • 發佈:2018-12-27
一、遍歷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);
}