# Java Lambada常用操作

Java Lambada表达式

  • Lambada允许将一个函数作为方法的参数,使用Lambada可以将代码变得简洁。
遍历List集合

1.使用Lambada表达式类似与forEach

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
//froEace循环
for (Integer ret : list) {
     
	System.out.println(ret);
}

//使用Lambada表达式输出
list.stream().forEach(x -> System.out.println(x));
list.stream().filter(x -> x % 2 == 0).forEach(x -> System.out.println(x));

2.操作Map

@Test
 public void test1() {
     
     List<HashMap<String, String>> list = new ArrayList<>();
     for (int i = 0; i < 10; i++) {
     
         HashMap<String, String> map = new HashMap<>();
         map.put(String.valueOf("键" + i), String.valueOf(i));
         list.add(map);
     }
     //遍历HashMap得到其中的键
     list.stream().forEach(x -> {
     
         for (String y : x.keySet()) {
     
             System.out.println("输出的值为:" + y);
         }
     });
     //遍历HashMap得到其中的值
     list.stream().forEach(x -> {
     
         for (Map.Entry y : x.entrySet()) {
     
             System.out.println("map中的值为:" + y);
         }
     });
 }
遍历Map
map.forEach((k, v) -> {
     
     System.out.println(k + "====" + v);
});
创建线程
public static void main(String[] args) {
     
       new Thread(() -> {
     
           System.out.println("我是进程1");
       }).start();
       new Thread(() -> {
     
           System.out.println("我是进程2");
       }).start();
       new Thread(() -> {
     
           System.out.println("我是进程3");
       }).start();
}
List转Map
@Test
public void test3() {
     
    List<Person> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
     
        Person person = new Person("Person" + i, String.valueOf(i));
        list.add(person);
    }
    Map<String, String> collect = list.stream().collect(Collectors.toMap(Person::getKey, Person::getValue));
    System.out.println(collect);
}
Map转List
@Test
public void test2() {
     
   HashMap<String, String> map = new HashMap<>();
   for (int i = 0; i < 10; i++) {
     
       map.put(String.valueOf("键" + i), String.valueOf(i));
   }
   System.out.println(map);
   //Map转List
   List<Person> collect = map.entrySet()
           .stream()
           .map(x -> new Person(x.getKey(), x.getValue()))
           .collect(Collectors.toList());
   for (Person x : collect) {
     
       System.out.println(x.getKey() + "====" + x.getValue());
   }
   map.forEach((k, v) -> {
     
       System.out.println(k + "====" + v);
   });
}

Map过滤
    @Test
    public void test6(){
     
        Map<String,String> map=new HashMap();
        map.put("1","3");
        map.put("1","1");
        map.put("3","4");
        map.put("4","6");

        Map<String, String> collect = map.entrySet().stream().filter(x -> String.valueOf(x.getKey()).equals("1")).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
        System.out.println(collect);
    }

你可能感兴趣的:(Java)