發表文章

目前顯示的是有「Lambda」標籤的文章

Java Lambda Map篇

目的 主要介紹Map中的新方法,包含如下 forEach() getOrDefault() putIfAbsent() remove() replace() replaceAll() merge() 有些是Lambda有些則是我覺得比以前使用Map更方便而介紹 forEach Map的forEach方法與List不大依樣,因為Map主要的迭代方法是以Entry為主,所以需要Key-Value Pair去迭代 原始碼解說 可以看到forEach的傳入參數BiConsumer介面,必須傳入Key與Val,裡面的實作就如同我們使用Java8版本以前的寫法,需要使用for迴圈去迭代抓出每個Value 原始碼 default void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } action.accept(k, v); } } 範例 private void forEachExample() { Map<Integer, String> map = new HashMap<>(); map.put(1, "test1"); map.put(2, "test2"); m...

Java Lambda Collection/List篇

Java Lambda Collection/List篇 前言 這篇文章主要接續Lambda基礎篇,主要介紹與自我複習常用的Collection家族中的Lambda方法 Collection forEach forEach 是Iterable介面中的default Method原始碼如下 default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } 敲黑板 畫重點 Collection透過FunctionalInterface "Consumer"讓此介面可以透過lambda實踐。 Collection家族都有實作Iterable介面因此都可以使用此forEach方法。 實踐 private void forExample(List<String> example) { example.forEach(System.out::println); } 透過ArrayList實踐 System.out::println省列了不帶任何參數的method ()->,讓Lambda自動對物件使用此method removeIf removeIf是Collection介面本身的方法,原始碼如下 default boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); boolean removed = false; final Iterator<E> each = iterator(); while (each.hasNext()) { if (filter.test(each.next())) { each.remove(); ...

Java Lambda 基礎

前言 Lambda語法對我而言較像是coding風格上的改變,讓程式碼風格更加地簡潔,如果程式碼更加簡潔那就代表 更容易被管理 容易管理代表容易擴張與除錯 容易擴張除錯也代表的迭代速度加快 速度加快代表產品更容易修改去符合使用者需求 產引更容易符合使用者需求代表公司賺大錢 我真心認為許多工程師常常覺得自己只是在寫Code,其實不然他們在幫助公司創造更多的機會養活更多的家庭與製造更多生產。 當然除了上述的優點之外,現在Java社群與官方也已經環繞著Lambda進行多種開發,這也代表使用Lambda可以讓工程師們減少重複的工作(而這些重複的工作Lambda提供的效能可能還比自己寫到好…汗顏) 內容中的原始碼可以參考我的GitHub! 點我! 甚麼是Lambda 先讓我們看一下使用Lambda前後的範例 無參數 使用執行續Print出字串 private void withoutLambda() { new Thread(new Runnable() { @Override public void run() { System.out.println("Hi! This function isn't using lambda"); } }).start(); } private void withLambda() { new Thread(() -> System.out.println("Hi! This function is using lambda") ).start(); } 有參數 將較長的字串往後移動 private void hasParameter() { List<String> list = Arrays.asList("Hi", "my", "name", "is", "Charlie"); ...