Операция Java-потока для проверки и возврата определенного объекта - PullRequest
0 голосов
/ 21 октября 2018

Я пытаюсь изучить Java Stream API и пишу несколько примеров.

Итак, мой пример выглядит следующим образом:

У меня есть список списков, каждый список может содержатьмного узлов.

Мне нужна программа, которая проверяет и возвращает узел, который удовлетворяет некоторому критерию.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
        public static void main( String[] args ) {
        ArrayList<ArrayList<Node>> lists =  new ArrayList<>();
        /*here i'm creating a list of 10 list from 0 to 9
        * and each list will have one node, the nodes will have a random 
        degree
        */
        IntStream.range(0,10).forEach(  index -> {
                                                lists.add(new ArrayList<>());
                                                int random=new Random().nextInt(10) + 1;
                                                lists.get(index).add(new Node(random));
        });

        Node specificLsit = getaSpecificNode(lists);
    }

   /*we chould retun a new Node(1) if there is a node that have a degree=1
    *and a new Node(2) id there is a node with degree= 2 
    *or null if the above condition fails.
    *so what is the java stream operation to writre for that purpose.
    */
    private static Node getaSpecificNode( ArrayList<ArrayList<Node>> lists ) {
        Node nodeToReturn =null;
        //code go here to return the desired result
        return nodeToReturn;
    }
}

class Node{
    int degree;

    Node(int degree){
        this.degree = degree;
    }
    @Override
    public String toString() {
        return this.degree+"";
    }
}

Цикл 2 for легко решить проблему, но мне нужно решение, котороеиспользует поток API.

То, что я пробовал:

 private static Node getaSpecificNode( ArrayList<ArrayList<Node>> lists ) {
    Node nodeToReturn =null;
    lists.forEach((list)->{
        list.forEach((node)->{
            if (node.degree ==1 || node.degree ==2 )
                nodeToReturn = node;

        });

    });
    return nodeToReturn ;
}

К сожалению, я получаю ошибку компиляции, что переменная nodeToReturn должна быть окончательной, но в моем случае я пытаюсьизмените его.

Есть ли лучшее решение?

1 Ответ

0 голосов
/ 21 октября 2018

Это должно сработать:

lists.stream().flatMap(List::stream).filter(e -> e.getDegree() == 1 || e.getDegree() == 2)
              .findAny()
              .orElse(null);

Здесь мы конвертируем ArrayList<ArrayList<Node>> в flatMap и затем применяем фильтр в зависимости от вашего состояния.Если совпадение найдено, возвращается Node, иначе возвращается ноль.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...