您的位置:首页 > 编程语言 > Java开发

[转]Java8 lambda表达式及新特新

2016-04-15 17:16 477 查看
分享自:Vincent

package info.liuwenjun.test;

import org.junit.Test;

import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

/**
* Created by Vincent on 2016-04-12.
*/
public class TestJava8 {

private void print(Object obj) {
System.out.println(obj);
}

@Test
public void sort() {
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");

Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareTo(b);
}
});

Collections.sort(names, (String a, String b) -> {
return a.compareTo(b);
});

Collections.sort(names, (String a, String b) -> a.compareTo(b));

Collections.sort(names, (a, b) -> a.compareTo(b));

print(names);

new Thread(new Runnable() {
@Override
public void run() {
System.out.println("inner class");
}
}).start();

new Thread(() -> System.out.println("lambda")).start();
}

@Test
public void typeDeduction() {
Function<Integer, String> intToStr = a -> a.toString();

Function<Double, String> doubleToStr = a -> a.toString();

// doubleToStr = intToStr;

// () -> print("typeDeduction");
((Action) () -> print("typeDeduction")).action();
}

@FunctionalInterface
private interface Action {
void action();
}

@Test
public void functionalInterface() {
Function<Integer, Integer> plusOne = i -> i + 1;
print(plusOne.apply(1));

Predicate<Character> emoticon = o->'皿'<-o;
print(emoticon.test('皿'));

Consumer<Integer> printInt = i -> print(i);
printInt.accept(1);

Supplier<Long> getCurrentTime = () -> System.currentTimeMillis();
print(getCurrentTime.get());

Action sayHello = () -> print("hello");
sayHello.action();
}

@Test
public void testThis() {
Action innerClass = new Action() {
@Override
public void action() {
this.print("testThis");
}

private void print(Object obj) {
System.out.println("Inner: " + obj);
}
};
innerClass.action();

Action lambda = () -> this.print("testThis");
lambda.action();
}

@Test
public void testFinal() {
final int finalVar = 0;
int effectivelyFinalVar = 0;
// effectivelyFinalVar = 1;

new Action() {
@Override
public void action() {
print(finalVar);
print(effectivelyFinalVar);
}
}.action();
}

private List<String> stringCollection = new ArrayList<String>() {
{
add("ddd2");
add("aaa2");
add("bbb1");
add("aaa1");
add("bbb3");
add("ccc");
add("bbb2");
add("ddd1");
}
};

@Test
public void filter() {
stringCollection
.stream()
.filter(s -> s.startsWith("a"))
.forEach(s -> print(s));
}

@Test
public void sorted() {
stringCollection
.stream()
.sorted((a, b) -> b.compareTo(a))
.filter(s -> s.startsWith("a"))
.forEach(s -> print(s));
}

@Test
public void map() {
stringCollection
.stream()
.map(s -> s.toUpperCase())
.sorted(Comparator.comparing(s -> s.length()))
.forEach(s -> print(s));
}

@Test
public void flatMap() {
stringCollection
.stream()
.filter(s -> s.startsWith("a"))
.flatMap(s -> Arrays.stream(s.split("")))
.forEach(c -> print(c));
}

@Test
public void match() {
print(stringCollection.stream().anyMatch(s -> s.startsWith("a")));

print(stringCollection.stream().allMatch(s -> s.startsWith("a")));

print(stringCollection.stream().noneMatch(s -> s.startsWith("z")));
}

@Test
public void count() {
print(stringCollection.stream().filter(s -> s.startsWith("b")).count());
}

@Test
public void reduce() {
Optional<Integer> optional = stringCollection
.stream()
.map(s -> s.length())
.reduce((a, b) -> a + b);
print(optional.get());

int sum = stringCollection.get(0).length();
for (int i = 1; i < stringCollection.size(); i++) {
sum = sum + stringCollection.get(i).length();
}
print(sum);
}

@Test
public void intStream() {
IntSummaryStatistics statistics = stringCollection
.stream()
.mapToInt(s -> s.length())
.summaryStatistics();
print(statistics.getAverage());
print(statistics.getSum());
print(statistics.getMax());
print(statistics.getMin());
print(statistics.getCount());
}

@Test
public void complex() {
stringCollection
.stream()
.sorted()
.filter(s -> s.startsWith("a") && s.endsWith("1"))
.map(s -> s.length())
.filter(i -> i == 4)
.forEach(i -> print(i));
}

@Test
public void toList() {
List<Integer> len = stringCollection.stream().map(s -> s.length()).collect(Collectors.toList());
print(len);
}

@Test
public void toMap() {
Map<String, Integer> len = stringCollection.stream().collect(Collectors.toMap(s -> s, s -> s.length()));
print(len);
}

@Test
public void groupingBy() {
Map<Integer, List<String>> groups = stringCollection
.stream()
.collect(Collectors.groupingBy(s -> s.length()));
print(groups);
}

@Test
public void complexCollect() {
Map<Integer, List<String>> groups = stringCollection
.stream()
.collect(Collectors.groupingBy(s -> s.length(),
Collectors.mapping(s -> s.toUpperCase(), Collectors.toList())));
print(groups);
}

@Test
public void removeIf() {
List<String> copy = new ArrayList<>(stringCollection);

stringCollection.removeIf(s -> s.startsWith("a"));
print(stringCollection);

Iterator<String> iter = copy.iterator();
while (iter.hasNext()) {
if(iter.next().startsWith("a")) {
iter.remove();
}
}
print(copy);
}

@Test
public void iterateMap() {
Map<String, Integer> map = stringCollection.stream().collect(Collectors.toMap(s -> s, s -> s.length()));

map.forEach((key, value) -> print(key + ": " + value));

print("---------");

for(Map.Entry entry : map.entrySet()) {
print(entry.getKey() + ": " + entry.getValue());
}
}

@Test
public void mapStream() {
Map<String, Integer> map = stringCollection.stream().collect(Collectors.toMap(s -> s, s -> s.length()));

map.entrySet()
.stream()
.filter(e -> e.getValue() == 4)
.forEach(e -> print(e.getKey() + ": " + e.getValue()));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: