# Set Lambda expression
Language:
Suitable for server development: JAVA.net PHT c++, c ASP golang python...
Front end: ios android H5 jsp...
Database: MySQL Oracle BD2 Hbase MonggoDB redis, SQL sever...
Big data: hadoop flume spark hive yarn zonokeeprer kafka sqoop,HDFS mr,scala...
Lambda expression:
With only one abstract method interface and the new feature of java 8, java can be programmed in a functional way, taking a substantial step in concurrency performance.
Compare Lambda with anonymous inner classes (lambda is a simple anonymous inner class)
1. Anonymous inner classes can create instances for any interface, no matter how many abstract methods the interface contains, as long as anonymous inner classes implement all abstract methods; but Lambda expressions can only create instances for functional interfaces (that is, only one abstract method).
2. Anonymous inner classes can create instances for abstract and even ordinary classes; however, Lambda expressions can only create instances for functional interfaces.
3. The method body of abstract methods implemented by anonymous inner classes allows the invocation of default methods defined in interfaces; however, the code block of Lambda expressions does not allow the invocation of default methods in interfaces.
Basic Grammar
1. Composition: (parameter) - > expression, (parameter) - > {method body;}
2. Parametric List: Parametric List allows omitting parameter types. If there is only one parameter in parametric list, parentheses in parametric list can also omit code.
3. Arrows (->): Must be made up of a line number and a greater than sign in English.
4. Code Block: If the code block contains only one statement and the lambda expression allows the curly brackets to be omitted from the code block, then the statement should not end with curly brackets.
5. Return value: The lambda code block has only one return statement, and even omits the return keyword. (The lambda expression needs to return a value, and only one statement in its code block omits return. The lambda expression automatically returns the result of this statement.)
6.lambda expressions can be directly used as parameters of functions. When an abstract function with only one interface is implemented, lambda expressions can be more flexible.
7.lambda expression type: It is defined as an interface, if there is only one explicitly declared abstract method, then it is a functional interface. Generally marked with @Functional Interface (or unlabeled), functional interfaces can be
There are multiple default or static methods, but only one abstract method can be declared. The main function of @FuctionalInterface is to check whether the current interface is a functional interface.
8. If global variables are used directly, if local variables are used directly, final will be added in front by default (as constants, similar to the case where local variables are used in local internal classes).
Method Reference and Constructor Reference
1. Reference class methods
//* 1. Reference class methods interface Converter{ //Converting strings to integers Integer convert(String value); } class Test1{ public static void fun1() { //The original method Converter converter = value->Integer.valueOf(value); Integer v1 = converter.convert("222"); System.out.println(v1); //Simplify //Reference Class Method //By:: Implemented, the parameters of lambda expression method are automatically passed to the current method. Converter converter2 = Integer::valueOf; Integer v2 = converter2.convert("333"); System.out.println(v2); } }
2. Instance Method of Referring to Specific Objects
//* 2. Instance Method of Referring to Specific Objects interface IA{ public void show(String message); } class A{ public void play(String i) { System.out.println("Here is A Method play"+" i:"+i); } } class Test2{ public static void fun2() { //Original IA ia = message->new A().play(message); ia.show("hello"); //Simplify IA ia2 = new A()::play; ia2.show("world"); } }
3. Example Method of Referring to a Class of Objects
//* 3. Example Method of Referring to a Class of Objects interface IB{ String subString(String string,int stat,int end); } class Test3{ public static void fun3() { //Original IB ib = (string,stat,end)->string.substring(stat, end); String sub1 = ib.subString("hello world", 2, 4); System.out.println(sub1); //Simplify //The first parameter of the implemented method in the functional interface acts as the caller, and all the later parameters are passed to the method. IB ib2 = String::substring; String sub2 = ib2.subString("class is over", 2, 5); System.out.println(sub2); } }
4. Reference Construction
interface IC{ Object show(String name,int age); } class Person{ String name; int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } } class Test4{ public static void fun4() { IC ic = (name,age)->new Person(name, age); Object per = ic.show("bing", 19); System.out.println(per); //Simplification //The construction method refers to the substitution of lambda expression, and all the parameters of the implemented method in the functional interface are passed as parameters. IC ic2 = Person::new; Object per1 = ic2.show("chen", 10); System.out.println(per1); } }
aggregate
Collections can store reference data types and different data types.
Sets and arrays
Array: Multiple data of different types can be stored. Data types can be simple data types or reference data types.
Disadvantage: Create a fixed value, can only store fixed length of data, once full, can not continue to store
2. Collections: Multiple data of different types can be stored, but only reference data types can be stored.
Disadvantage: Only reference data types can be stored
Advantages: Storage space increases with the increase of storage data. Reasonable utilization of memory space
Classification:
- Collection:--- Interface
list-interface
ArrayList - Class
Vector - - - Class
LinKedList - Class
Set - - - Interface
HasSet - - - Class
TreeSet - - - Class
- Map: - Interface
hashMap -- Class
TreeSet - Class
ArrayList
Method:
1. Add: collection.add("java");
2. Delete: Boolean remove (Object o); void clear () clear!= null // clear () can also save data
3. Judgment: boolean contains(Object o) // The underlying is equals, which is the equals of Object o calls
4. Judgment: boolean isEmpty()// Judgment set is empty!= null
5. Collection variable array: Collection variable array: Object[] objects = collection.toArray() when no one wants to change the length of the collection;
Traversal: Fault-tolerant processing and downward transformation are required when different types of data exist in the set at the same time.
1. Iterator traversal:
hasnext(): To determine whether there are elements in the current location, return TRUE if there are elements and false if there are no elements.
next(); takes the value of the current position out and moves the pointer back to a position.
** Get iterators: 1. Create objects 2. Bind to collections
Iterator iterator()// Gets objects in a collection
Code example:
while (iterator1.hasNext()) {
Object object = iterator 1. next ();// polymorphism
If (object instance of String) {// Fault-tolerant Processing
System.out.println("iterator2:"+object);
}
}
2. Enumerator traversal:
Enumeration enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
Object object = (Object) enumeration.nextElement();
System.out.println(object);
}
List set comparison
1.List: Accessed data is ordered (elements are stored in the same order as elements are added) and repeatable
ArrayList; The underlying data structure is array, thread safety, features: fast search speed, slow add and delete speed,
Vector: The underlying data structure is arrays, thread-safe. Features: fast search speed, slow add-delete speed
LinkedList: The bottom is linked list, thread is not safe. Features: slow search speed, add and delete speed.
2.Set: Stored data types are disorderly and unrepeatable.
List common methods:
1. Increase:
void add(int index, E element)
boolean addAll()
2. delete
E remove(int index) // Returns deleted elements
3. Modification
E set(int index, E element)
4. Finding (iterator) can be modified concurrently: adding elements while traversing
ListIterator listIteator(int index)
public static void test(List list) { //Get the iterator object first ListIterator listIterator = list.listIterator(); //From left to right while (listIterator.hasNext()) { String object = (String) listIterator.next(); System.out.println("From left to right:"+object); } //From right to left while (listIterator.hasPrevious()) { String object = (String)listIterator.previous(); System.out.println("From right to left:"+object); } //Internally, there are add,set,remove methods, which can directly operate on the elements of the current location. //From left to right while (listIterator.hasNext()) { String object = (String) listIterator.next(); if (object.equals("haha")) { //During the use of iterators, deleting elements directly using the list deletion method can cause errors, so don't do this //list.remove(object); //Using the remove method of iterator //Using the method provided by the iterator, note: remove,add,set should not be used at the same time listIterator.remove(); } System.out.println("From left to right:"+object); } }
During the use of iterators, deleting elements directly using the list deletion method can cause errors, so don't do this
vector
1. The enumerator is used in traversal.
Enumeration enumeration = vector.elements();
while(enumeration.hasMoreElements()){
Object object = (Object) enumeration.nextElement();
System.out.println(object);
}
LindedList
1.addFirst(); add from the beginning
2.addLast(); add from the end
3.getFirst();
4.removeFirst()
5.removeLast()
Since JDK 1.6:
1.offerFirst()// Deposit Value
2.offerLast()
3.peekFirst()// Returns NULL when the fetch object does not exist
4.peekLast()
5. PolFirst ()// Deleted objects do not exist and return NULL
6.pollLast()
Set s are non-repeatable and disorderly
1. HashSet: The underlying hash table, thread insecurity
2. TreeSet: The bottom is a binary tree, and threads are insecure
HashSet
1. Principle: To achieve de-duplication by calling hashCode and equals methods of elements. First, the hashCode method is called to get the hash code value of the current object, so that the hash code value of the two objects can be compared. If they are different, they are directly considered to be two objects instead of calling equals. If they continue to call equals method, they will return true. Think of it as an object, and vice versa think of it as two objects.
2. Call hashCode first and then equals.
Question: Why rewrite hashCode()? To repeat
TreeSet allows sorting and de-duplication
Implementing Comparable Interface: Natural Sorting
1. TreeSet's add method achieves sorting, de-duplication, and calls the element's CompareTo method (String has implemented the CompareTo interface)
2. Objects that do not implement Compareble interface cannot be treated as elements of TreeSet, otherwise exception ClassCastException is reported.
3. CompareTo returns 0 with only one element; returns 1 how to save and how to fetch; - 1 reverse order
4. Example code:
@Override public int compareTo(Object o) { //Comparisons Based on Rules Made by oneself //Comparisons by age and name //fault tolerant if (!(o instanceof Person2)) { throw new ClassCastException("Type conversion error"); } //Downward transition Person2 person2 = (Person2)o; //First name int num = this.name.compareTo(person2.name);//String has implemented CompareTO, //Age ratio return num==0?this.age-person2.age:num; }
Comparator interface: manual sorting
Steps:
1. Create a comparator class: Implement Comparator
lass ComStrWithLength implements Comparator{ @Override public int compare(Object o1, Object o2) { //Compare the length of strings if (!(o1 instanceof String)) { throw new ClassCastException("Type conversion error"); } if (!(o2 instanceof String)) { throw new ClassCastException("Type conversion error"); } //Downward transition String s1 = (String)o1; String s2 = (String)o2; //First according to the length ratio int num = s1.length()-s2.length(); //Length is the same, then in dictionary order return num==0?s1.compareTo(s2):num; } }
2. Create comparator objects:
ComStrWithLength comStrWithLength = new ComStrWithLength();
3. Give the comparator object to TreeSet:
Set set = new TreeSet<>(comStrWithLength);
Note: Manual sorting takes precedence over default sorting
generic paradigm
1. Originally, a collection can store any reference type, but if it is later, it has to be fault-tolerant and transitional downward. Generics are designed to solve the above problems, so that you can clearly understand what is in the collection.
2. Transfer error detection from run-time to compile-time. Improve safety and efficiency.
Principle: The return value of add() before is object, and after that, the return value of add() is String.
Note: Generic use: classes, methods, interfaces
1. Equivalent to defining a type. When the generic type is determined, the type is determined.
1. Use generics on classes
class Student1<E>{ E tools; public E getTools() { return tools; } public void setTools(E tools) { this.tools = tools; } }
2. Use generics in methods: generics can be used to define more than one at a time.
1. Methodological generics are consistent with generics on classes
class Dog{
// 1. Generics on methods are consistent with generics on classes
public void eat(F f) {
System.out.println(f);
}
}
2. Use generics independently: Note that generics must be defined before they are used. The way to define generics is to add <generics> at the front of the current method. Function: Keep generics in the same way as those in the method.
public void song(E e) {
ArrayList arrayList = new ArrayList<>();
System.out.println(e);
}
3. Using generics in static methods: Must be used independently, by defining generics after static <generics>
public static <W> void show(W w) {}
3. Use generics on interfaces: Our main research is how generics on subclasses of interfaces are used.
1. Generics on subclasses are consistent with those on interfaces: generics on classes are determined, generics on interfaces are determined, and generics on methods are determined.
2. Use generics on interfaces and no generics on subclasses: a specific generic type must be specified at the interface location of the implementation
interface Inte<E>{ public void show(E e); } //1. Generics on subclasses are consistent with interfaces /* Generics on classes are determined, generics on interfaces are determined, and generics on methods are determined. */ class Pig<E> implements Inte<E>{ @Override public void show(E e) { System.out.println(e); } } //2. Use generics on interfaces and no generics on subclasses /*A specific generic type must be specified at the interface location of the implementation * * Methods In the case of generics: * 1.If the method is overridden, generics are consistent with interfaces * 2.If the subclass has its own method, it can be consistent with the interface, or it can have its own generics. */ class Bird implements Inte<String>{ public void show(String e) {}; }
### Limit Upper Limit and Limit Offline
/* * About the use of?In java 1)Used for?: Here is part of the arithmetic operator. The first is the judgment condition, and the second is the result of two branches. 2)sql statement for database: select * from emp * where * name =?: represents placeholder 3)Used for generics to represent any data type. //Object here has nothing to do with the previous one? Class<?> class1 = Object.class; //If the generic type of a class is written as? Yes. As a return value, it defaults to Object type, but not as a parameter. So when specifying a generic type for an object, it is necessary to write a specific type. Test<?> test = new Test(); //test.run(new Object()); class Test<T>{ T e; public T run(T a) { T t = null; return t; } } */ /* * Understanding: * * ?:Wildcards, which can represent one or more data types * Limit upper limit: <? Extends E>: Limit the whole <> preferable generic type upper limit is E,<> preferable type is the subclass of E and E. * Limit Lower Limit: <? Super E>:: Limit the whole <> acceptable generic type lower limit is E, and the preferable type in <> is the parent class of E and E. * * * Limitation cap: <? Extends E > */ public class Demo14 { public static void main(String[] args) { // ArrayList<Student2> list1 = new ArrayList<>(); list1.add(new Student2("bingbing", 1)); //Reference can be passed: Because Student2 is a subclass of Person1, traversal can be achieved. bianli(list1); ArrayList<Teacher> list2 = new ArrayList<>(); list2.add(new Teacher("bingbing", 1)); //Reference can be passed: Teacher1 is a subclass of Person1, which enables traversal bianli(list2); ArrayList<Person4> list3 = new ArrayList<>(); list3.add(new Person4("bingbing", 1)); //It can be transmitted for reference. bianli(list3); ArrayList<Object> list4 = new ArrayList<>(); list4.add(new Object()); //References: Object is the parent of Person1 and cannot be traversed //bianli(list4); } public static void bianli(Collection<? extends Person4> e){ System.out.println("Traversed"); } } class Person4{ String name; int age; public Person4() { super(); // TODO Auto-generated constructor stub } public Person4(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person4 [name=" + name + ", age=" + age + "]"; } } class Teacher extends Person4{ public Teacher(String name, int age) { super(name, age); } } class Student2 extends Person4 { public Student2(String name, int age) { super(name, age); } }