Java8文章
Android/AS对Java8的支持
Java8示例
public class T1 {
public static void main(String[] args) {
T1 t = new T1();
t.OptionalUse();
}
public void f1() {
List<Person> list = Arrays.asList(new Person(10, 10), new Person(11, 11), new Person(30, 30),
new Person(12, 12));
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return ((Integer) o1.getWeight()).compareTo((Integer) o2.getWeight());
}
});
for (Person item : list) {
System.out.println("Persion info:" + item);
}
}
public void f1t1() {
List<Person> list = Arrays.asList(new Person(10, 10), new Person(11, 11), new Person(30, 30),
new Person(12, 12));
list.sort(Comparator.comparing(Person::getWeight));
for (Person item : list) {
System.out.println("Persion info:" + item);
}
}
public boolean isOld(Fruit fruit) {
return Integer.parseInt(fruit.getName()) <= 3;
}
public boolean isLow(Fruit fruit) {
return fruit.getPrice() < 10;
}
public List<Fruit> filterFruit(List<Fruit> fruits, Predicate<Fruit> p) {
List<Fruit> result = new ArrayList<>();
for (Fruit item : fruits) {
if (p.test(item)) {
result.add(item);
}
}
return result;
}
public void f2() {
List<Fruit> ori = Arrays.asList(new Fruit("1", 1), new Fruit("2", 2), new Fruit("3", 20), new Fruit("4", 8));
System.out.println("old Fruit:");
List<Fruit> old = filterFruit(ori, (Fruit f) -> Integer.parseInt(f.getName()) <= 3);
for (Fruit item : old) {
System.out.println("Fruit info:" + item);
}
System.out.println();
System.out.println("low Fruit:");
List<Fruit> low = filterFruit(ori, (Fruit f) -> f.getPrice() < 10);
for (Fruit item : low) {
System.out.println("Fruit info:" + item);
}
}
public void f3() {
Imp1 imp = new Imp1();
imp.df1();
}
private List<Fruit> gainFruits() {
List<Fruit> fruits = Arrays.asList(new Fruit("1", 1), new Fruit("6", 6), new Fruit("3", 3), new Fruit("10", 10),
new Fruit("2", 2));
return fruits;
}
public void f4() {
List<Fruit> fruits = gainFruits();
Collections.sort(fruits, new Comparator<Fruit>() {
@Override
public int compare(Fruit o1, Fruit o2) {
return o1.getPrice() > o2.getPrice() ? 1 : (o1.getPrice() == o2.getPrice() ? 0 : -1);
}
});
System.out.println("原始写法:");
for (Fruit item : fruits) {
System.out.println(item);
}
System.out.println("仅保留(o1,o2):");
fruits = gainFruits();
Collections.sort(fruits,
(o1, o2) -> o1.getPrice() > o2.getPrice() ? 1 : (o1.getPrice() == o2.getPrice() ? 0 : -1));
for (Fruit item : fruits) {
System.out.println(item);
}
System.out.println("Comparator.comparing:");
fruits = gainFruits();
Collections.sort(fruits, Comparator.comparing(Fruit::getPrice));
for (Fruit item : fruits) {
System.out.println(item);
}
System.out.println("直接使用 list.sort:");
fruits = gainFruits();
fruits.sort(Comparator.comparing(Fruit::getPrice));
for (Fruit item : fruits) {
System.out.println(item);
}
}
private interface i1{
void f1(Object object);
}
public void testLambdaReturn(List<Integer> objs,i1 i1) {
for(Object obj : objs) {
System.out.println("obj is? before:" + obj);
i1.f1(obj);
System.out.println("obj is? after:" + obj);
}
}
public void f5() {
List<Integer> objs = Arrays.asList(1,2,3,4,5);
testLambdaReturn(objs, (obj) -> {obj = 0;});
}
interface functionalInterface{
void f();
}
interface functionalInterface1{
void f1();
void f2();
}
public void testFI(functionalInterface fi) {
fi.f();
}
public void testFI1(functionalInterface1 fi1) {
fi1.f2();
}
public void f6() {
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("r1.run");
}
};
r1.run();
Runnable r2 = () -> System.out.println("r2.run");
r2.run();
testFI(() -> System.out.println("Lambda表达式直接创建函数式接口实例"));
}
private List gainList() {
return Arrays.asList(1,2,3,4,5);
}
private void f71(List items, Predicate p) {
for(Object item:items) {
if(p.test(item)) {
System.out.println("f71. pass. item:" + item);
}
}
}
private void f72(List items, Consumer c) {
for(Object item:items) {
c.accept(item);
}
}
private void f73(List items, Function f) {
int hashCode;
for(Object item:items) {
hashCode = Integer.parseInt(f.apply(item).toString()) + 10;
System.out.println("f73. hashCode:" + hashCode);
}
}
private void f74(List items, Supplier s) {
Object result;
for(Object item:items) {
result = s.get();
System.out.println("f74. result:" + result);
}
}
public void f7() {
List list = gainList();
f71(list,T -> true);
f72(list,T -> System.out.println("hashCode:" + T.hashCode()));
f73(list,T -> T.hashCode());
f74(list,() -> Math.random() * 100);
}
interface i81{
void f();
}
interface i82{
void f();
}
interface i83{
void f(Object p1,Object p2);
}
private void f8FI(i81 i81) {
i81.f();
System.out.println("f8FI. i81");
}
private void f8FI(i82 i82) {
i82.f();
System.out.println("f8FI. i82");
}
private void f8FI(i83 i83) {
i83.f(1, 2);
}
public void f8() {
f8FI((p1,p2) -> System.out.println("i83 结果:" + (p1.hashCode() + p2.hashCode())));
}
private int num = 10;
public void f9() {
Runnable runnable = () -> num = 20;
runnable.run();
System.out.println("num:" + num);
}
public void f10t(Consumer<Person> consumer,Person person) {
consumer.accept(person);
}
public void f10() {
Person p = new Person(10,200);
f10t(P -> {P.age = 100; P.weight = 100;}, p);
System.out.println(p);
Person p1 = new Person(10,200);
f10t(P -> P = new Person(300, 300), p1);
System.out.println(p1);
}
private Person createPerson() {
Person p = new Person((int) (Math.random() * 10000), (int) (Math.random() * 10000));
return p;
}
public void f11() {
List<Person> persons = Arrays.asList(createPerson(),createPerson(),createPerson(),createPerson(),createPerson(),createPerson());
System.out.println("原始Person集合:");
persons.forEach(P -> System.out.println(P));
List<Integer> ages = persons.stream().map(Person::getAge).collect(Collectors.toList());
System.out.println("最终Age集合");
ages.forEach(A -> System.out.println(A));
}
public void fCompoundLambda() {
List<Person> persons = Arrays.asList(
createPerson(),createPerson(),createPerson(),createPerson(),createPerson(),createPerson(),
new Person(4000, 666),new Person(4000, 667),new Person(4000, 668),new Person(4000, 669),createPerson(),createPerson()
);
persons.sort(Comparator.comparing(Person::getAge));
System.out.println("按照年龄升序排列:");
persons.forEach(p -> System.out.println(p));
persons.sort(Comparator.comparing(Person::getAge).reversed());
System.out.println("按照年龄降序排列:");
persons.forEach(p -> System.out.println(p));
persons.sort(Comparator.comparing(Person::getAge).thenComparing(Comparator.comparing(Person::getWeight).reversed()));
System.out.println("先按照年龄升序排列,再按照体重降序排列");
persons.forEach(p -> System.out.println(p));
Predicate<Person> ori = (p) -> p.getAge() > 5000;
Predicate<Person> negate = ori.negate();
System.out.println("年龄不大于5000:");
persons.forEach(p -> {
if(negate.test(p)) {
System.out.println(p);
}
});
Predicate<Person> and = ori.and((p) -> p.getWeight() > 2000);
System.out.println("年龄大于5000且体重大于2000");
persons.forEach(p -> {
if(and.test(p)) {
System.out.println(p);
}
});
Predicate<Person> or = ori.or((p) -> p.getWeight() > 2000);
System.out.println("年龄大于5000或体重大于2000");
persons.forEach(p -> {
if(or.test(p)) {
System.out.println(p);
}
});
Function<Integer, Integer> f1 = (p) -> p + 1;
Function<Integer, Integer> f2 = (p) -> p * 3;
Function<Integer, Integer> andThen = f1.andThen(f2).andThen(f2);
Function<Integer, Integer> compose = f1.compose(f2).compose(f2);
int a1 = andThen.apply(1);
int a2 = compose.apply(1);
System.out.println("试验Function复合函数");
System.out.println(a1);
System.out.println(a2);
}
public void streamUse() {
List<Person> persons = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
persons.add(createPerson());
}
List<Integer> ages =
persons.stream()
.filter(p -> p.getAge() >= 4000)
.sorted(Comparator.comparing(Person::getWeight)).map(Person::getAge).collect(Collectors.toList());
ages.forEach(a -> System.out.println("年龄:" + a));
}
public void streamAndCollection() {
List<String> colors = Arrays.asList("赤","橙","黄","绿","青","蓝","紫");
Stream<String> stream = colors.stream();
stream.forEach(s -> System.out.println("颜色:" + s));
stream.forEach(s -> System.out.println("颜色:" + s));
}
private List<Person> gainPersons(int count) {
List<Person> persons = new ArrayList<>();
for (int i = 0; i < count; i++) {
persons.add(createPerson());
}
return persons;
}
public void streamAndOpt() {
List<Person> persons = gainPersons(20);
List<Integer> ages = persons.stream()
.filter(p -> p.getAge() >= 4000)
.limit(7)
.map(Person::getAge)
.collect(Collectors.toList());
ages.forEach(System.out::println);
}
public void streamDistinct() {
List<Integer> numbers = Arrays.asList(1,2,1,3,4,5,4,5,6,0,8,0);
numbers.stream().filter(n -> n%2==0)
.forEach(System.out::println);
System.out.println("distinct去重");
numbers.stream().filter(n -> n%2==0)
.distinct()
.forEach(System.out::println);
}
public void streamSkip() {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8);
numbers.stream()
.forEach(System.out::println);
System.out.println("skip跳过");
numbers.stream()
.skip(3)
.forEach(System.out::println);
}
public void streamFlatMap() {
List<String> strs = Arrays.asList("WhosWhos","Party?Party?");
List<String[]> c1 = strs.stream().map(t -> t.split("")).distinct().collect(Collectors.toList());
List<Stream<String>> c2 = strs.stream().map(t -> t.split("")).map(Arrays::stream).distinct().collect(Collectors.toList());
List<String> c3 = strs.stream().map(t -> t.split("")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
System.out.println("\n遍历c1");
c1.forEach(c -> Arrays.asList(c).forEach(System.out::print));
System.out.println("\n遍历c2");
c2.forEach(c -> c.forEach(System.out::print));
System.out.println("\n遍历c3");
c3.forEach(System.out::print);
}
public void streamMatch() {
List<Person> persons = gainPersons(10);
System.out.println("原始集合:");
persons.forEach(p -> System.out.println(p + "\t"));
boolean m1 = persons.stream().anyMatch(p -> p.getWeight() >= 9999);
boolean m2 = persons.stream().allMatch(p -> p.getWeight() >= 1000);
boolean m3 = persons.stream().noneMatch(p -> p.getWeight() >= 9999);
System.out.println("有人体重>=9999:" + m1 + " ; 所有人体重>=1000:" + m2 + " ; 没有人体重>=9999:" + m3);
}
public void streamFind() {
List<Person> persons = gainPersons(10);
System.out.println("原始集合:");
persons.forEach(p -> System.out.println(p + "\t"));
Person p1 = persons.stream().filter(p -> p.getWeight() >= 5000).findAny().get();
Person p2 = persons.stream().filter(p -> p.getWeight() >= 5000).findFirst().get();
System.out.println("任意1个体重>=5000的人:" + p1 + " ; 第一个体重>=5000的人:" + p2);
}
public void streamReduce() {
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer n1 = nums.stream().reduce(0, (a, b) -> a + b);
Integer n2 = nums.stream().reduce(0, Integer::sum);
Integer n3 = nums.stream().reduce(Integer::sum).get();
System.out.println("元素求和. n1:" + n1 + " ; n2:" + n2 + " ; n3:" + n3);
Integer n4 = nums.stream().reduce(0, (a, b) -> Math.max(a, b));
Integer n5 = nums.stream().reduce(0, Integer::max);
Integer n6 = nums.stream().reduce(Integer::max).get();
System.out.println("元素最大值. n4:" + n4 + " ; n5:" + n5 + " ; n6:" + n6);
Integer n7 = nums.stream().reduce(Integer.MAX_VALUE, (a, b) -> Math.min(a, b));
Integer n8 = nums.stream().reduce(Integer.MAX_VALUE, Integer::min);
Integer n9 = nums.stream().reduce(Integer::min).get();
System.out.println("元素最小值.n7:" + n7 + " ; n8:" + n8 + " ; n9:" + n9);
}
public void streamCreate() {
try {
Stream<String> strs = Files.lines(Paths.get("files.txt"),StandardCharsets.UTF_8);
strs.forEach(System.out::println);
strs.close();
} catch (Exception e) {
e.printStackTrace();
}
Stream.of(1,2,3);
Stream.empty();
Stream.generate(() -> Math.random())
.limit(20)
.forEach(System.out::println);
Stream.iterate(100, (p) -> p+10)
.limit(20)
.forEach(System.out::println);
IntStream.rangeClosed(1, 20)
.forEach(System.out::println);
}
private void StreamCollectors() {
List<Person> persons = Arrays.asList(new Person(100, 100), new Person(101, 100), new Person(102, 100),
new Person(103, 100), new Person(100, 100), new Person(101, 100), new Person(102, 100),
new Person(103, 100));
Map<Integer, List<Person>> map = persons.stream().collect(Collectors.groupingBy(Person::getAge));
for (Entry<Integer, List<Person>> entry : map.entrySet()) {
System.out.println("当前年龄:" + entry.getKey());
entry.getValue().forEach(System.out::println);
}
long count = persons.stream().count();
System.out.println("集合中元素数量:" + count);
Person max = persons.stream().collect(Collectors.maxBy(Comparator.comparing(Person::getAge))).get();
System.out.println("年龄最大Person:" + max);
Person min = persons.stream().collect(Collectors.minBy(Comparator.comparing(Person::getAge))).get();
System.out.println("年龄最小Persion:" + min);
int sum = persons.stream().collect(Collectors.summingInt(Person::getAge));
System.out.println("年龄总和:" + sum);
Double avg = persons.stream().collect(Collectors.averagingInt(Person::getAge));
System.out.println("年龄均值:" + avg);
String ages = persons.stream().map(Person::getAge).map(i -> ""+i).collect(Collectors.joining("-", "before ", " after"));
System.out.println("每个Person年龄:" + ages);
Map<Integer, Long> ageCount = persons.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
System.out.println("每个年龄对应的人数:");
for(Entry<Integer, Long> entry:ageCount.entrySet()) {
System.out.println(entry);
}
System.out.println("先按年龄分组,再按体重分组:");
Map<Integer, Map<String, List<Person>>> ageWeight = persons.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(p -> {
if(((Person) p).getAge() >= 100) {
return "large";
}else {
return "small";
}
})));
System.out.println(ageWeight);
System.out.println("找出每个年龄最重的Person:");
Map<Integer, Person> ageMaxWeight = persons.stream().collect(
Collectors.groupingBy(Person::getAge,
Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Person::getWeight)), Optional::get)));
System.out.println(ageMaxWeight);
}
public void OptionalUse() {
double gamePrice = Optional.ofNullable(new PC()).map(PC::getGame).map(Game::getPrice).orElse(100.00D);
System.out.println("游戏价格:" + gamePrice);
System.out.println("试验空Optionnal.get : "+Optional.ofNullable(null).get());
}
}