gpt4 book ai didi

java - 随机 int 流到通用链表

转载 作者:行者123 更新时间:2023-11-29 08:29:14 26 4
gpt4 key购买 nike

在我正在进行的编码练习中,我尝试生成 25 个随机整数并使用对它们进行排序的函数将它们插入到链表中。我了解如何分别执行这些任务,但我想尝试将它们作为一个流来执行。这是我编写的代码,用于使用示例列表进行设置,以确保 insertSorted 函数正常工作。

节点.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;
}

}

排序列表.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();
}

}

主程序.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 );

我已经在 J​​ava8 和 Java9 上对此进行了验证,所以现在我不确定什么时候需要它,或者什么时候改变了它。

关于java - 随机 int 流到通用链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49683795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com