簡體   English   中英

隨機int流到泛型鏈表

[英]Random int stream to generic linked list

在我正在進行的編碼練習中,我試圖生成25個隨機整數,並使用對它們進行排序的函數將它們插入到鏈表中。 我了解如何分別執行這些任務,但是我想嘗試將它們作為流完成。 這是我編寫的用於通過示例列表進行設置的代碼,以確保insertSorted函數正常工作。

Node.java

class Node<T extends Comparable<T>> {
    T data;
    Node<T> nextNode;

    Node(T data) {
        this(data, null);
    };

    Node(T data, Node<T> nextNode){
        this.data = data;
        this.nextNode = nextNode;
    };

    void setNext(Node<T> next){
        nextNode = next;
    }

}

SortedList.java

import java.util.NoSuchElementException;

class SortedList<T extends Comparable<T>> {
    private Node<T> firstNode;
    private Node<T> lastNode;
    private String name;

    SortedList(String listName){
        name = listName;
        firstNode = lastNode = null;
    }

    void insertSorted(T item){
        if(isEmpty()){
            lastNode = new Node<T>(item);
            firstNode = lastNode;
        } else if(firstNode.data.compareTo(item) > 0){
            firstNode = new Node<T>(item, firstNode);
        }
        else {
            Node<T> compareNode = firstNode;
            while(compareNode.nextNode != null
            && compareNode.nextNode.data.compareTo(item) < 0){
                compareNode = compareNode.nextNode;
            }
            Node<T> itemNode = new Node<T>(item, compareNode.nextNode);
            compareNode.setNext(itemNode);
        }
    }

    private boolean isEmpty() { return firstNode == null; }

    void print() {
        if (isEmpty()){
            System.out.printf("Empty %s%n", name);
            return;
        }

        System.out.printf("%s is: ", name);
        Node<T> current = firstNode;

        while (current != null){
            System.out.printf("%s ", current.data);
            current = current.nextNode;
        }
        System.out.println();
    }

}

Main.java

class Main{
    public static void main(String[] args){

        // sample example
        SortedList<Integer> sample = new SortedList<>("sample list");
        sample.insertSorted(84);
        sample.insertSorted(65);
        sample.insertSorted(134);
        sample.insertSorted(102);
        sample.insertSorted(954);
        sample.insertSorted(755);

        sample.print();
    }
}

我知道我可以使用以下代碼從流中生成隨機整數數組:

int[] arr = new SecureRandom().ints(25, 0, 100).toArray();

我如何使用insertSorted方法在上面的SortedList對象中包含隨機的int流?

SortedList::insertSorted(T t)看起來像Consumer<T> ,因此您可以使用接受消費者作為參數的流函數,例如.forEach(...)

new SecureRandom().ints(25, 0, 100)
    .boxed()
    .forEach( sample::insertSorted );

正如@Holger在評論中提到的那樣, .boxed()是不必要的。

new SecureRandom().ints(25, 0, 100)
    .forEach( sample::insertSorted );

我已經在Java8和Java9上對此進行了驗證,所以現在我不確定何時需要它,或者什么時候需要更改。

暫無
暫無

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

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