With the newly added Lambda expressions in Java 8, we can easily operate large collections in parallel. We have
just come into contact with java8, and Lambda is still very useful, and I have not touched much at present. Let me give you a few examples (there will be supplements about Lambda in the future). I will also continue to update this blog)
Without further ado, let's go directly to the example
1. Use stream().forEach() to process List in a loop;
- List<String> list = Lists.newArrayList(); //Guava package provided by google for creating a new List com.google.common.collect;
- list.add("1");
- list.add("2");
- list.add("3");
- list.stream().forEach(string ->{
- System.out.println(string);
- });
- operation result:
- 1
- 2
- 3
List<String> list = Lists.newArrayList();//Guava package provided by google for creating a new List com.google.common.collect; list.add("1"); list.add("2"); list.add("3"); list.stream().forEach(string ->{ System.out.println(string); }); operation result: 1 2 3
2. Use stream().map() to process List and assign a value to another List:
- List<String> list1 = Lists.newArrayList();
- List<String> list2 = Lists.newArrayList();
- list1.add("1");
- list1.add("2");
- list1.add("3");
- list2 = list1.stream().map(string -> {
- return "stream().map() after processing: " + string;
- }).collect(Collectors.toList());
- list2.stream().forEach(string -> {
- System.out.println(string);
- });
- operation result:
- After stream().map() processing: 1
- After stream().map() processing: 2
- After stream().map() processing: 3
List<String> list1 = Lists.newArrayList(); List<String> list2 = Lists.newArrayList(); list1.add("1"); list1.add("2"); list1.add("3"); list2 = list1.stream().map(string -> { return "stream().map() after processing: " + string; }).collect(Collectors.toList()); list2.stream().forEach(string -> { System.out.println(string); }); operation result: After stream().map() processing: 1 After stream().map() processing: 2 After stream().map() processing: 3
3. Use stream().filter() to process the List and filter the List:
- List<String> list1 = Lists.newArrayList();
- List<String> list2 = Lists.newArrayList();
- list1.add("1");
- list1.add("1");
- list1.add("2");
- list1.add("3");
- list2 = list1.stream().filter(s -> s != "1").collect(Collectors.toList());
- System.out.println(list2.toString());
- operation result:
- [2, 3]