如何在堆栈中创建堆栈?喜欢
[[1 2 3][3 4 5][6 7 8]]因此,有三个子堆栈,如[123]、[456]、[789],它们位于主堆栈中。如何使用Java中的堆栈内置函数创建它?
发布于 2018-01-30 20:25:08
根据第一个元素表示1,4,7,顺序是7,4,1,但其他元素完好无损。排序后的结果是[7,8,9,4,5,6,1,2,3]。如果我的堆栈是这样的,像[ 1,10,5,5,11,15,4,9,2]。排序后得到的结果类似于[5,11,15,4,9,2,1,10,5]。因此,这意味着只有第一个元素将被排序其余的相同。
我认为您可以使用Comparator(来自Java8,它是@FunctionalInterface),例如:
Stack<Stack<Integer>> stacks = new Stack<>();
// Previous example
// ...
//straight Comparator
Comparator<Stack<Integer>> byFirst = Comparator.comparingInt(Stack::firstElement);
//reverse Comparator
Comparator<Stack<Integer>> reverseByFirst
= (Stack<Integer> s1, Stack<Integer> s2)
-> s2.firstElement().compareTo(s1.firstElement());
// or = (Stack<Integer> s1, Stack<Integer> s2)-> s2.get(0).compareTo(s1.get(0));
// get Stack
stacks = Stream.of(stackI1,stackI2,stackI3)
// .sorted(byFirst) // byFirst
.sorted(reverseByFirst) // reverse
.collect(Collector.of(
() -> new Stack(),
(s,b)->s.push(b),
(b1, b2) -> (Stack) b1.push(b2)
)
);
System.out.println(stacks); //[[7, 8, 9], [4, 5, 6], [1, 2, 3]]我觉得这有帮助..。
发布于 2018-01-30 04:06:51
您可以使用lambda表达式(如果我正确理解您的问题):
Stack<Integer> stackI1 = new Stack<>();
stackI1.push(1);
stackI1.push(2);
stackI1.push(3);
Stack<Integer> stackI2 = new Stack<>();
stackI2.push(4);
stackI2.push(5);
stackI2.push(6);
Stack<Integer> stackI3 = new Stack<>();
stackI3.push(7);
stackI3.push(8);
stackI3.push(9);
Stack<Stack<Integer>> stacks = new Stack<>();
stack.push(stackI1);
stack.push(stackI2);
stack.push(stackI3);
System.out.println(stacks); //[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/**
* lambda expressions
*/
// stacks = stacks.stream()
stacks = Stream.of(stackI1,stackI2,stackI3)
.collect(Collector.of(
() -> new Stack(),
(s,b)->s.push(b),
(b1, b2) -> (Stack) b1.push(b2)
)
);
System.out.println(stacks); //[[1, 2, 3], [4, 5, 6], [7, 8, 9]]也许这会有所帮助:example => Collector.of(...)。
https://stackoverflow.com/questions/48513532
复制相似问题