簡體   English   中英

在Java 8中使用流在列表上進行迭代

[英]Iterating on list with stream in java 8

用Java 8 stream()重寫此迭代的最佳方法是什么。

for (name : names){
  if(name == a){
    doSomething();
    break;
  }
  if(name == b){
   doSomethingElse();
   break; 
 }
 if(name == c){
  doSomethingElseElse();
  break;
 }
}

基本上,如果滿足三個條件,則使用3個條件遍歷列表要中斷循環,並且在每個條件下都要調用不同的方法。

您可以使用anyMatch查找符合您條件之一的第一個元素並終止。 使用副作用來調用處理方法:

boolean found =
  names.stream()
       .anyMatch (name -> {
                  if (name.equals(a)) {
                    doSomething();
                    return true;
                  } else if (name.equals(b)) {
                    doSomethingElse ();
                    return true;
                  } else if (name.equals(c)) {
                    doSomethingElseElse ();
                    return true;
                  } else {
                    return false;
                  }
                }
              );

很難看,但是在一次迭代中您做了什么。

Eran的答案絕對是執行搜索的直接方法。 但是,我想提出一種稍微不同的方法:

private static final Map<String, Runnable> stringToRunnable = new HashMap<>();

{
  stringToRunnable.put("a", this::doSomething);
  stringToRunnable.put("b", this::doSomethingElse);
  stringToRunnable.put("c", this::doSomethingElseElse);
}

public static void main(String[] args) {
  List<String> names = Arrays.asList("1", "2", "b", "a");
  names.stream()
      .filter(stringToRunnable::containsKey)
      .findFirst()
      .ifPresent(name -> stringToRunnable.get(name).run());
}

private void doSomethingElseElse() {
}

private void doSomethingElse() {
}

public void doSomething() {
}

起作用的部分是下面的代碼,但我假設abc是字符串,將其添加到main()函數中。 但是,該想法適用於任何數據類型。

names.stream()
    .filter(stringToRunnable::containsKey)
    .findFirst()
    .ifPresent(name -> stringToRunnable.get(name).run());

這個想法是保留鍵和Runnable的映射。 通過將Runnable作為值,可以定義不帶參數的void方法引用。 流首先過濾掉地圖中不存在的所有值,然后找到第一個匹配項,並在找到后執行其方法。

Collection collection;
collection.forEach(name->{
    if(name.equals(a))){
       doSomething();

    }
    if(name.equals(b)){
        doSomethingElse();

    }
    if(name.equals(c)){
        doSomethingElseElse();

    }
});

暫無
暫無

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

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