簡體   English   中英

Java,如何使用computeIfAbsent computeIfPresent 來實現這個目的?

[英]Java, how to use computeIfAbsent computeIfPresent to fulfil this purpose?

我正在嘗試創建一個具有以下功能的工廠:

  • 它應該總是返回一個過濾器對象。

  • 從 hashmap = 如果字符串字母(鍵)已經存在於 hashmap 中,它應該只從 hashmap 中獲取它的值(對象)並返回它。

  • 或者如果哈希圖沒有該鍵則創建一個新對象然后創建一個新對象並返回它。

該程序應根據用戶輸入按以下順序工作:

 //user first input. 
 String letters="aaa"; // creat new object. 
 //user second input. 
 String letters="fff"; // creat new object. 

 String letters="aaa"; //dont make a new object and return the object and return the object of the first input.

為此,我想到了以下幾點:

  • 我首先想到的是使用哈希圖。
  • 通過將String letters指定為鍵,將對象Filter為值。
  • 接下來我想比較之前是否沒有輸入過密鑰,如果密鑰已經存在則創建一個新對象,然后返回它的對象。

這是我暫時寫的:

(工廠類)

 //if i let this i will getjava.lang.NullPointerException
 //private static Filter filter = null;
 public static Filter getFilter(String letters){

        Filter filter=new Filter(letters);

        HashMap <String, Object> hmap = new HashMap< String , Object> ();

        hmap.put(letters,filter);

        //for the first run is true because the map has yet only one pair of <k,v>
        if (hmap.containsKey(letters))
        {
            System.out.println("return the obj where there is a key match");//i will remove this later cz the user doesnt care about it. 
            //so i will return the filter object that has been created here "hmap.put(letters,filter);" by returning the value that matches the key.
            return (Filter) hmap.get(letters);  

        } else {//if the user didn't enter the same key then a new object shall be created!.

            System.out.println("new object has been generated");//i will remove this late cz the user doent care about it.
            //if the entered letters(key) isnt found in the map then put it in the map and creat new object. 
            hmap.put(letters, filter);

            return filter;
        }
    }

另一個類中的構造函數受到保護,工廠將從主方法中獲取每個用戶輸入的字符串字母。 任何幫助將不勝感激,但請在 Java 代碼中展示您的建議。

好吧,這顯然不能解決問題,但如何解決問題?

所以我在網上搜索並找到了computeIfAbsent,但我不知道如何使用它。 在 java orcale doc 上,這是寫的和
hmap.computeIfAbsent(letters, k -> new Filter (k) );

現在我不明白這個“k”在這里是什么意思,也不明白這個“->”是什么意思我試圖像上面那樣使用它,但我遇到了一些錯誤:

  • k 不能解析為變量
  • 預期標記“-”、“--”的語法錯誤
  • l 無法解析為變量

    1. 第一個問題,當使用computeIfAbsent 時,代碼應該是什么樣子的?
    2. 無論如何,我可以在不使用那些 computeIfAbsent 和 coputeIfPresent 的情況下獲得我想要的東西嗎?

我已經在類過濾器中有以下內容

public class Filter {
private final String letters;

    protected Filter(String letters) {
        this.letters = letters;
    }
public static void main(String[] args) {
while(true){
    //Scanner to allow user to give input!.
    Scanner in =new Scanner(System.in);

    System.out.println("please enter the filter stirng!");

    String filter= in.next();
 }
}


 public static Filter getFilter(String letters) {
          Filter obj = hmap.get(letters);
          if (obj == null) {
             obj = new Filter(letters);
             hmap.put(letters, obj);
          }
          return obj;
       }

嘗試這個


    public static void main(String[] args) {
          Filter f = FilterFactory.getFilter("aaa"); // call from user1
          Filter g = FilterFactory.getFilter("bbb"); // call from user2
          Filter h = FilterFactory.getFilter("aaa"); // call from user3
          System.out.println(f == h); // same filter
    }

    class FilterFactory {
       private static Map<String, Filter> map = new HashMap<>();

       private FilterFactory() {
       }

       public static Filter getFilter(String letters) {
          return map.computeIfAbsent(letters, Filter::new);
       }

 // Pre-java 8 version
       public static Filter getFilter2(String letters) {
          Filter f = map.get(letters);
          if (f == null) {
             f = new Filter(letters);
             map.put(letters, f);
          }
          return f;
       }

    class Filter {
       String f;

       public Filter(String f) {
          this.f = f;
       }

       public String toString() {
          return f;
       }
    }

在所有情況下,hashMap 的 Key 是過濾器構造函數的參數。

  • 對於方法引用,它是隱含的。
  • 對於 lambda,它是局部變量(在上面的例子中是 k)。

注意:此操作需要 Java 8+。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM