堆栈子堆栈创建

时间:2018-01-30 03:40:30

标签: java collections stack

如何在堆栈中创建堆栈?像

[[1 2 3][3 4 5][6 7 8]]

所以有三个子包,例如[123][456][789],它们位于主堆栈中。如何使用Java中的函数堆栈构建来创建它?

2 个答案:

答案 0 :(得分:0)

您可以使用 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(...)

答案 1 :(得分:0)

  

基于第1个元素表示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(来自 Java 8 它是@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]]

我认为这有帮助...

相关问题