public class People {
//该类写在记事本里,在用javac命令行编译成class文件,放在d盘根目录下
private String name;
public People() {}
public People(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "I am a people, my name is " + name;
}
}
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
public class MyClassLoader extends ClassLoader
{
public MyClassLoader()
{
}
public MyClassLoader(ClassLoader parent)
{
super(parent);
}
protected Class> findClass(String name) throws ClassNotFoundException
{
File file = new File("D:/People.class");
try{
byte[] bytes = getClassBytes(file);
//defineClass方法可以把二进制流字节组成的文件转换为一个java.lang.Class
Class> c = this.defineClass(name, bytes, 0, bytes.length);
return c;
}
catch (Exception e)
{
e.printStackTrace();
}
return super.findClass(name);
}
private byte[] getClassBytes(File file) throws Exception
{
// 这里要读入.class的字节,因此要使用字节流
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel wbc = Channels.newChannel(baos);
ByteBuffer by = ByteBuffer.allocate(1024);
while (true){
int i = fc.read(by);
if (i == 0 || i == -1)
break;
by.flip();
wbc.write(by);
by.clear();
}
fis.close();
return baos.toByteArray();
}
}
MyClassLoader mcl = new MyClassLoader();
Class> clazz = Class.forName("People", true, mcl);
Object obj = clazz.newInstance();
System.out.println(obj);
System.out.println(obj.getClass().getClassLoader());//打印出我们的自定义类加载器
interface Formula {
double calculate(int a);
default double sqrt(int a) {
return Math.sqrt(a);
}
}
Formula formula = new Formula() {
@Override
public double calculate(int a) {
return sqrt(a * 100);
}
};
formula.calculate(100); // 100.0
formula.sqrt(16); // 4.0
List names = Arrays.asList("peterF", "anna", "mike", "xenia");
Collections.sort(names, new Comparator() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});
Collections.sort(names, (a, b) -> b.compareTo(a));
代码实现:
public interface Converter {
T convert(F from);
}
public class Test {
public static void main(String[] args) {
Converter converter = (from) -> Integer.valueOf(from);
Integer convert = converter.convert("123");
System.out.println(convert);
}
}
结果:
public static void main(String[] args) {
Converter converter = (from) -> Integer.valueOf(from);
Integer convert = converter.convert("123");
System.out.println(convert);
Converter converter1 = Integer::valueOf;
Integer convert1 = converter1.convert("123");
System.out.println(convert1);
}
public class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
public interface PersonFactory {
Person create(String firstName, String lastName);
}
public static void main(String[] args) {
PersonFactory personFactory = Person::new;
Person person = personFactory.create("A", "B");
System.out.println(person.firstName);
}
我们可以直接在lambda表达式中访问外层的局部变量:
final int num = 1;
Converter stringConverter =
(from) -> String.valueOf(from + num);
System.out.println(stringConverter.convert(123));
int num1 = 1;
Converter stringConverter1 =
(from) -> String.valueOf(from + num1);
System.out.println(stringConverter1.convert(125));
int num2 = 1;
Converter stringConverter3 =
(from) -> String.valueOf(from + num2);
num2 = 3;
public class Lambda4 {
static int outerStaticNum;
int outerNum;
void testScopes() {
Converter stringConverter1 = (from) -> {
outerNum = 23;
return String.valueOf(from);
};
}
public static void main(String[] args) {
Converter stringConverter2 = (from) -> {
outerStaticNum = 72;
return String.valueOf(from);
};
System.out.println(stringConverter2.convert(123));
}
}
Predicate predicate = (str) -> str.toString().length() > 4;
boolean foo = predicate.test("foo");
boolean foo1 = predicate.negate().test("foo");
System.out.println(foo);
System.out.println(foo1);
Predicate nonNull = Objects::nonNull;
nonNull.test(null);
List stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
stringCollection
.stream()
.filter((s) -> s.toString().startsWith("a"))
.forEach(System.out::println);
Sort 排序
stringCollection
.stream()
.sorted()
.filter((s) -> s.toString().startsWith("a"))
.forEach(System.out::println);
stringCollection
.stream()
.map(String::toUpperCase)
.sorted((a, b) -> b.compareTo(a))
.forEach(System.out::println);
boolean anyStartsWithA =
stringCollection
.stream()
.anyMatch((s) -> s.startsWith("a"));
System.out.println(anyStartsWithA);
// true
long startsWithB =
stringCollection
.stream()
.filter((s) -> s.startsWith("b"))
.count();
System.out.println(startsWithB);
b开头元素个数: 3
Optional reduced =
stringCollection
.stream()
.sorted()
.reduce((s1, s2) -> s1 + "," + s2);
System.out.println(reduced.get());
逗号隔开
int max = 1000000;
List values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
UUID uuid = UUID.randomUUID();
values.add(uuid.toString());
}
long t0 = System.nanoTime();
long count = values.stream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("sequential sort took: %d ms", millis));
// 串行耗时: 899 ms
long t0 = System.nanoTime();
long count = values.parallelStream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("parallel sort took: %d ms", millis));
// 并行排序耗时: 472 ms
Mapmap = new HashMap<>(); for (int i = 0; i < 10; i++) {map.putIfAbsent(i, "val" + i);}map.forEach((id, val) -> System.out.println(val));
map.computeIfPresent(3, (num, val) -> val + num);
map.get(3); // val33
map.computeIfPresent(9, (num, val) -> null);
map.containsKey(9); // false
map.computeIfAbsent(23, num -> "val" + num);
map.containsKey(23); // true
map.computeIfAbsent(3, num -> "bam");
map.get(3); // val33
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
map.get(9); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
map.get(9); // val9concat