Java 8 指南
Contents
比较器
以前的用法:
Comparator<Developer> byName = new Comparator<Developer>() {
@Override
public int compare(Developer o1, Developer o2) {
return o1.getName().compareTo(o2.getName());
}
};
lambda:
Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());
Map, List 中的 forEach
Map
Map<String, Integer> items = new HashMap<>();
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
List
List<String> items = new ArrayList<>();
items.forEach(item->System.out.println(item));
Stream filter
List<String> lines = Arrays.asList("spring", "node", "mkyong");
List<String> result = lines.stream() // convert list to stream
.filter(line -> !"mkyong".equals(line)) // we dont like mkyong
.collect(Collectors.toList()); // collect the output and convert streams to a List
result.forEach(System.out::println); //output : spring, node
Stream map
List<String> alpha = Arrays.asList("a", "b", "c", "d");
List<String> collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
Stream groupby
List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");
Map<String, Long> result = items.stream().collect( Collectors.groupingBy( Function.identity(), Collectors.counting()));
System.out.println(result);
Stream to List
Stream<String> language = Stream.of("java", "python", "node");
//Convert a Stream to List
List<String> result = language.collect(Collectors.toList());
result.forEach(System.out::println);
Array to Stream
String[] array = {"a", "b", "c", "d", "e"};
//Arrays.stream
Stream<String> stream1 = Arrays.stream(array);
stream1.forEach(x -> System.out.println(x));
重用 Stream
String[] array = {"a", "b", "c", "d", "e"};
Supplier<Stream<String>> streamSupplier = () -> Stream.of(array);
//get new stream
streamSupplier.get().forEach(x -> System.out.println(x));
//get another new stream
long count = streamSupplier.get().filter(x -> "b".equals(x)).count();
System.out.println(count);
Sort Map
by key
Map<String, Integer> unsortMap = new HashMap<>();
Map<String, Integer> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
by value
Map<String, Integer> unsortMap = new HashMap<>();
Map<String, Integer> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
List to Map
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", 80000));
Map<Integer, String> result1 = list.stream().collect(Collectors.toMap(Hosting::getId, Hosting::getName));
map filter
Map<Integer, String> map = new HashMap<>();
String result = map.entrySet().stream()
.filter(x -> "something".equals(x.getValue()))
.map(x->x.getValue())
.collect(Collectors.joining());
Map<Integer, String> collect = map.entrySet().stream()
.filter(x -> x.getKey() == 2)
.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
flat map
String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};
//Stream<String[]>
Stream<String[]> temp = Arrays.stream(data);
//Stream<String>, GOOD!
Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));
Map to List
Map<Integer, String> map = new HashMap<>();
List<Integer> result = map.keySet().stream().collect(Collectors.toList());
List<String> result2 = map.values().stream().collect(Collectors.toList());
join
List<String> list = Arrays.asList("java", "python", "nodejs", "ruby");
String result = list.stream().map(x -> x).collect(Collectors.joining(" | "));
String result = String.join(", ", list);
StringJoiner sj = new StringJoiner("/", "prefix-", "-suffix");
sj.add("2016");
sj.add("02");
sj.add("26");
String result = sj.toString(); //prefix-2016/02/26-suffix
Read file by line
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
list.forEach(System.out::println);
String to char array
String password = "password123";
password.chars() //IntStream
.mapToObj(x -> (char) x)//Stream<Character>
.forEach(System.out::println);
int array to List
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// IntStream.of or Arrays.stream, same output
//List<Integer> list = IntStream.of(number).boxed().collect(Collectors.toList());
List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());
System.out.println("list : " + list);
检测数组是否包含特定值
String[] alphabet = new String[]{"A", "B", "C"};
boolean result = Arrays.stream(alphabet).anyMatch("A"::equals);
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
boolean result = IntStream.of(number).anyMatch(x -> x == 4);
TemporalAdjusters
LocalDate localDate = LocalDate.now();
System.out.println("current date : " + localDate);
LocalDate with = localDate.with(TemporalAdjusters.firstDayOfMonth());
System.out.println("firstDayOfMonth : " + with);
自定义
public class NextChristmas implements TemporalAdjuster {
@Override
public Temporal adjustInto(Temporal temporal) {
return temporal.with(ChronoField.MONTH_OF_YEAR, 12).with(ChronoField.DAY_OF_MONTH, 25);
}
}
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
System.out.println("current date : " + localDate);
localDate = localDate.with(new NextChristmas());
System.out.println("Next Christmas : " + localDate);
}