基于合并标准有效地合并列表

时间:2015-11-06 18:57:20

标签: java algorithm data-structures merge

我有三个排序列表,我想按照以逗号分隔的字符串派生的特定顺序合并为一个。这三个列表如下所示:

List<Square> squares;
List<Ball> balls;
List<Triangle> triangles;

现在我想将所有这些列表合并到形状列表中,其中Shape是要添加到此列表的父类,不会破坏任何内容。

List<Shape> shapes

每个列表按每个列表类型对象上的id排序。合并顺序基于此字符串提供的顺序(我可以更好地表示,因为这是超级hacky):

String mergeOrder = "Ball, Triangle, Squares"

根据上面的合并顺序,我想按照上面的顺序从每个列表中取一个形状,并添加到形状列表,直到其中一个列表用完对象。此时,合并顺序应继续使用其余列表。即:

Balls List:
12
16
20

Triangles List:
1

Squares List:
9
10

Merged List:
12 -> Ball
1 -> Triangle
9 -> Square
16 -> Ball
10 -> Square (Triangles ran out)
20 -> Ball (Squares ran out)

进行此类合并过程的最佳方法是什么?任何代码片段/骷髅都会有很大的帮助!

1 个答案:

答案 0 :(得分:2)

以下是示例代码

public class Main {

   private static class Shape {

      private final String value;

      private final String type;

      public Shape(String type, String value) {
         this.type = type;
         this.value = value;
      }

      @Override
      public String toString() {
         return type + "[" + value + "]";
      }
   }

   public static void main(String[] args) {
      List<Shape> balls = new ArrayList<>();
      List<Shape> triangles = new ArrayList<>();
      List<Shape> squares = new ArrayList<>();
      balls.add(new Shape("Ball", "10"));
      balls.add(new Shape("Ball", "12"));
      balls.add(new Shape("Ball", "16"));
      triangles.add(new Shape("Triangle", "1"));
      squares.add(new Shape("Square", "4"));
      squares.add(new Shape("Square", "5"));

      List<Iterator<Shape>> shapes = new ArrayList<>();
      shapes.add(balls.iterator());
      shapes.add(triangles.iterator());
      shapes.add(squares.iterator());

      List<Shape> merged = new ArrayList<>();

      boolean finished = false;
      while (!finished) {
         boolean hasNext = false;
         for (Iterator<Shape> iterator : shapes) {
            hasNext = hasNext || iterator.hasNext();
            if (iterator.hasNext()) {
               merged.add(iterator.next());
            }
         }
         finished = !hasNext;
      }

      System.out.println(merged);

   }
}

更新:

使用流进行迭代:

  boolean finished = false;
  while (!finished) {
     List<Iterator<Shape>> iteratorsWithNext = shapes.stream().filter(
           s -> s.hasNext()).collect(Collectors.toList());
     iteratorsWithNext.forEach(it -> merged.add(it.next()));
     finished = iteratorsWithNext.isEmpty();
  }

输出

[Ball[10], Triangle[1], Square[4], Ball[12], Square[5], Ball[16]]