日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java 8流:Micro Katas

發布時間:2023/12/3 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java 8流:Micro Katas 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

編程kata是一種練習,可以幫助程序員通過練習和重復練習來磨練自己的技能。

本文是“ 通過Katas進行Java教程 ”系列的一部分。

本文假定讀者已經具有Java的經驗,熟悉單元測試的基礎知識,并且知道如何從他最喜歡的IDE(我是IntelliJ IDEA )運行它們。

下面顯示的練習背后的想法是,使用測試驅動的開發方法來學習Java 8 Streaming(編寫第一個測試的實現,確認它通過并轉到下一個測試)。

每個部分都將以測試形式的目標開始,以證明實現一旦編寫便是正確的。 這些測試中的每一個都在Java 7(或更早版本)和Java 8中使用Streams進行了一種可能的實現。 這樣,讀者可以將Java 8的某些新功能與早期JDK中的等效功能進行比較。 請嘗試解決測試,而不查看提供的解決方案。

有關TDD最佳實踐的更多信息,請閱讀“ 測試驅動開發(TDD):使用Java示例的最佳實踐” 。

Java 8地圖

將集合的元素轉換為大寫。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.ToUpperCase.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Convert elements of a collection to upper case.*/ public class ToUpperCaseSpec {@Testpublic void transformShouldConvertCollectionElementsToUpperCase() {List<String> collection = asList("My"< "name"< "is"< "John"< "Doe");List<String> expected = asList("MY"< "NAME"< "IS"< "JOHN"< "DOE");assertThat(transform(collection)).hasSameElementsAs(expected);}}

Java 7(transform7)和Java8(transform)實現

package com.technologyconversations.java8exercises.streams;import java.util.ArrayList; import java.util.List;import static java.util.stream.Collectors.toList;public class ToUpperCase {public static List<String> transform7(List<String> collection) {List<String> coll = new ArrayList<>();for (String element : collection) {coll.add(element.toUpperCase());}return coll;}public static List<String> transform(List<String> collection) {return collection.stream() // Convert collection to Stream.map(String::toUpperCase) // Convert each element to upper case.collect(toList()); // Collect results to a new list}}

Java 8過濾器

過濾集合,以便僅返回少于4個字符的元素。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.FilterCollection.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Filter collection so that only elements with less then 4 characters are returned.*/ public class FilterCollectionSpec {@Testpublic void transformShouldFilterCollection() {List<String> collection = asList("My", "name", "is", "John", "Doe");List<String> expected = asList("My", "is", "Doe");assertThat(transform(collection)).hasSameElementsAs(expected);}}

Java 7(transform7)和Java8(transform)實現

package com.technologyconversations.java8exercises.streams;import java.util.ArrayList; import java.util.List;import static java.util.stream.Collectors.toList;public class FilterCollection {public static List<String> transform7(List<String> collection) {List<String> newCollection = new ArrayList<>();for (String element : collection) {if (element.length() < 4) {newCollection.add(element);}}return newCollection;}public static List<String> transform(List<String> collection) {return collection.stream() // Convert collection to Stream.filter(value -> value.length() < 4) // Filter elements with length smaller than 4 characters.collect(toList()); // Collect results to a new list}}

Java 8 FlatMap

展平多維集合。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.FlatCollection.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Flatten multidimensional collection*/ public class FlatCollectionSpec {@Testpublic void transformShouldFlattenCollection() {List<List<String>> collection = asList(asList("Viktor", "Farcic"), asList("John", "Doe", "Third"));List<String> expected = asList("Viktor", "Farcic", "John", "Doe", "Third");assertThat(transform(collection)).hasSameElementsAs(expected);}}

Java 7(transform7)和Java8(transform)實現

package com.technologyconversations.java8exercises.streams;import java.util.ArrayList; import java.util.List;import static java.util.stream.Collectors.toList;public class FlatCollection {public static List<String> transform7(List<List<String>> collection) {List<String> newCollection = new ArrayList<>();for (List<String> subCollection : collection) {for (String value : subCollection) {newCollection.add(value);}}return newCollection;}public static List<String> transform(List<List<String>> collection) {return collection.stream() // Convert collection to Stream.flatMap(value -> value.stream()) // Replace list with stream.collect(toList()); // Collect results to a new list}}

Java 8 Max和比較器

從集合中獲取最老的人。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.OldestPerson.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Get oldest person from the collection*/ public class OldestPersonSpec {@Testpublic void getOldestPersonShouldReturnOldestPerson() {Person sara = new Person("Sara", 4);Person viktor = new Person("Viktor", 40);Person eva = new Person("Eva", 42);List<Person> collection = asList(sara, eva, viktor);assertThat(getOldestPerson(collection)).isEqualToComparingFieldByField(eva);}}

Java 7(getOldestPerson7)和Java8(getOldestPerson)實現

package com.technologyconversations.java8exercises.streams;import java.util.Comparator; import java.util.List;public class OldestPerson {public static Person getOldestPerson7(List<Person> people) {Person oldestPerson = new Person("", 0);for (Person person : people) {if (person.getAge() > oldestPerson.getAge()) {oldestPerson = person;}}return oldestPerson;}public static Person getOldestPerson(List<Person> people) {return people.stream() // Convert collection to Stream.max(Comparator.comparing(Person::getAge)) // Compares people ages.get(); // Gets stream result}}

Java 8之和

對集合的所有元素求和。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.Sum.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Sum all elements of a collection*/ public class SumSpec {@Testpublic void transformShouldConvertCollectionElementsToUpperCase() {List<Integer> numbers = asList(1, 2, 3, 4, 5);assertThat(calculate(numbers)).isEqualTo(1 + 2 + 3 + 4 + 5);}}

Java 7(calculate7)和Java8(calculate)實現

package com.technologyconversations.java8exercises.streams;import java.util.List;public class Sum {public static int calculate7(List<Integer> numbers) {int total = 0;for (int number : numbers) {total += number;}return total;}public static int calculate(List<Integer> people) {return people.stream() // Convert collection to Stream.reduce(0, (total, number) -> total + number); // Sum elements with 0 as starting value}}

Java 8過濾器和映射

獲取所有孩子(18歲以下)的名字。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.Kids.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Get names of all kids (under age of 18)*/ public class KidsSpec {@Testpublic void getKidNameShouldReturnNamesOfAllKidsFromNorway() {Person sara = new Person("Sara", 4);Person viktor = new Person("Viktor", 40);Person eva = new Person("Eva", 42);Person anna = new Person("Anna", 5);List<Person> collection = asList(sara, eva, viktor, anna);assertThat(getKidNames(collection)).contains("Sara", "Anna").doesNotContain("Viktor", "Eva");}}

Java 7(getKidNames7)和Java8(getKidNames)實現

package com.technologyconversations.java8exercises.streams;import java.util.*;import static java.util.stream.Collectors.toSet;public class Kids {public static Set<String> getKidNames7(List<Person> people) {Set<String> kids = new HashSet<>();for (Person person : people) {if (person.getAge() < 18) {kids.add(person.getName());}}return kids;}public static Set<String> getKidNames(List<Person> people) {return people.stream().filter(person -> person.getAge() < 18) // Filter kids (under age of 18).map(Person::getName) // Map Person elements to names.collect(toSet()); // Collect values to a Set}}

Java 8摘要統計

獲取人員統計信息:平均年齡,人數,最大年齡,最小年齡和所有年齡的總和。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.PeopleStats.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Get people statistics: average age, count, maximum age, minimum age and sum og all ages.*/ public class PeopleStatsSpec {Person sara = new Person("Sara", 4);Person viktor = new Person("Viktor", 40);Person eva = new Person("Eva", 42);List<Person> collection = asList(sara, eva, viktor);@Testpublic void getStatsShouldReturnAverageAge() {assertThat(getStats(collection).getAverage()).isEqualTo((double)(4 + 40 + 42) / 3);}@Testpublic void getStatsShouldReturnNumberOfPeople() {assertThat(getStats(collection).getCount()).isEqualTo(3);}@Testpublic void getStatsShouldReturnMaximumAge() {assertThat(getStats(collection).getMax()).isEqualTo(42);}@Testpublic void getStatsShouldReturnMinimumAge() {assertThat(getStats(collection).getMin()).isEqualTo(4);}@Testpublic void getStatsShouldReturnSumOfAllAges() {assertThat(getStats(collection).getSum()).isEqualTo(40 + 42 + 4);}}

Java 7(getStats7)和Java8(getStats)實現

package com.technologyconversations.java8exercises.streams;import java.util.IntSummaryStatistics; import java.util.List;public class PeopleStats {public static Stats getStats7(List<Person> people) {long sum = 0;int min = people.get(0).getAge();int max = 0;for (Person person : people) {int age = person.getAge();sum += age;min = Math.min(min, age);max = Math.max(max, age);}return new Stats(people.size(), sum, min, max);}public static IntSummaryStatistics getStats(List<Person> people) {return people.stream().mapToInt(Person::getAge).summaryStatistics();}}

Java 8分區

分區成人和孩子。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List; import java.util.Map;import static com.technologyconversations.java8exercises.streams.Partitioning.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Partition adults and kids*/ public class PartitioningSpec {@Testpublic void partitionAdultsShouldSeparateKidsFromAdults() {Person sara = new Person("Sara", 4);Person viktor = new Person("Viktor", 40);Person eva = new Person("Eva", 42);List<Person> collection = asList(sara, eva, viktor);Map<Boolean, List<Person>> result = partitionAdults(collection);assertThat(result.get(true)).hasSameElementsAs(asList(viktor, eva));assertThat(result.get(false)).hasSameElementsAs(asList(sara));}}

Java 7(partitionAdults7)和Java8(partitionAdults)實現

package com.technologyconversations.java8exercises.streams;import java.util.*; import static java.util.stream.Collectors.*;public class Partitioning {public static Map<Boolean, List<Person>> partitionAdults7(List<Person> people) {Map<Boolean, List<Person>> map = new HashMap<>();map.put(true, new ArrayList<>());map.put(false, new ArrayList<>());for (Person person : people) {map.get(person.getAge() >= 18).add(person);}return map;}public static Map<Boolean, List<Person>> partitionAdults(List<Person> people) {return people.stream() // Convert collection to Stream.collect(partitioningBy(p -> p.getAge() >= 18)); // Partition stream of people into adults (age => 18) and kids}}

Java 8分組

按國籍分組人。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List; import java.util.Map;import static com.technologyconversations.java8exercises.streams.Grouping.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Group people by nationality*/ public class GroupingSpec {@Testpublic void partitionAdultsShouldSeparateKidsFromAdults() {Person sara = new Person("Sara", 4, "Norwegian");Person viktor = new Person("Viktor", 40, "Serbian");Person eva = new Person("Eva", 42, "Norwegian");List<Person> collection = asList(sara, eva, viktor);Map<String, List<Person>> result = groupByNationality(collection);assertThat(result.get("Norwegian")).hasSameElementsAs(asList(sara, eva));assertThat(result.get("Serbian")).hasSameElementsAs(asList(viktor));}}

Java 7(groupByNationality7)和Java8(groupByNationality)實現

package com.technologyconversations.java8exercises.streams;import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import static java.util.stream.Collectors.*;public class Grouping {public static Map<String, List<Person>> groupByNationality7(List<Person> people) {Map<String, List<Person>> map = new HashMap<>();for (Person person : people) {if (!map.containsKey(person.getNationality())) {map.put(person.getNationality(), new ArrayList<>());}map.get(person.getNationality()).add(person);}return map;}public static Map<String, List<Person>> groupByNationality(List<Person> people) {return people.stream() // Convert collection to Stream.collect(groupingBy(Person::getNationality)); // Group people by nationality}}

Java 8加入

返回用逗號分隔的人名。

測驗

package com.technologyconversations.java8exercises.streams;import org.junit.Test;import java.util.List;import static com.technologyconversations.java8exercises.streams.Joining.namesToString; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;/* Return people names separated by comma*/ public class JoiningSpec {@Testpublic void toStringShouldReturnPeopleNamesSeparatedByComma() {Person sara = new Person("Sara", 4);Person viktor = new Person("Viktor", 40);Person eva = new Person("Eva", 42);List<Person> collection = asList(sara, viktor, eva);assertThat(namesToString(collection)).isEqualTo("Names: Sara, Viktor, Eva.");}}

Java 7(namesToString7)和Java8(namesToString)實現

package com.technologyconversations.java8exercises.streams;import java.util.List;import static java.util.stream.Collectors.joining;public class Joining {public static String namesToString7(List<Person> people) {String label = "Names: ";StringBuilder sb = new StringBuilder(label);for (Person person : people) {if (sb.length() > label.length()) {sb.append(", ");}sb.append(person.getName());}sb.append(".");return sb.toString();}public static String namesToString(List<Person> people) {return people.stream() // Convert collection to Stream.map(Person::getName) // Map Person to name.collect(joining(", ", "Names: ", ".")); // Join names}}

資源

完整源代碼位于GitHub存儲庫https://github.com/vfarcic/java-8-exercises中 。 除了測試和實現之外,存儲庫還包含build.gradle,除其他外,build.gradle可用于下載AssertJ依賴項并運行測試。

翻譯自: https://www.javacodegeeks.com/2014/11/java-8-streams-micro-katas.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Java 8流:Micro Katas的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。