从java中的数组中删除空值

时间:2016-10-18 15:30:24

标签: java arrays

我有一个方法应该从数组中删除值...

public Application[] deleteApp(String id) {
        int count = 0;
        for (int i = 0; i < this.apps.length; i++) {
            if (this.apps[i] != null && this.apps[i].getId().equals(id)) {
                this.apps[i] = null;
                if (this.apps[i] == null)
                    count++;
            }
        }
        Application[] withoutNulls = new Application[this.apps.length - count];
        int index = 0;
        for (Application app : this.apps) {
            if (app != null) {
                withoutNulls[index] = app;
                index++;
            }
        }
        return withoutNulls;
    }

但最后的结果是如此:

Application[] app = {app1, app2, null};

出了什么问题?我正在计算空值,创建新数组[sizeOfArray - countOfNulls],并且只记录非空值:(

UPD 我对此进行了测试。

@Test
    public void deleteAppTest() {
        Tracker tracker = new Tracker();
        Application testing_1 = new Application();
        Application testing_2 = new Application();
        Application[] test = {testing_1};
        tracker.addApp(testing_1);
        tracker.addApp(testing_2);
        tracker.deleteApp(testing_2.getId());
        assertThat(tracker.showApps(), is(test));

但是方法没有通过测试。 预期:是[]      但是:是[,null]

1 个答案:

答案 0 :(得分:0)

尝试使用Lambdas

   public Application[] deleteApp(String id) {
      List<Application> result = Arrays.asList(apps).stream().
            filter(app -> app != null &&!id.equals(app.getId())).collect(Collectors.toList());
      return result.toArray(new Application[result.size()]);
  }

这是@Erwin Bolwidt建议的

public Application[] deleteApp(String id) {
      int count = 0;
      for (int i = 0; i < this.apps.length; i++) {
          if (this.apps[i] != null && this.apps[i].getId().equals(id)) {
              this.apps[i] = null;
              count++;
          }
          // Move this if out into an else if
          else if (this.apps[i] == null){
             count++;
          }
      }
      Application[] withoutNulls = new Application[this.apps.length - count];
      int index = 0;
      for (Application app : this.apps) {
          if (app != null) {
              withoutNulls[index] = app;
              index++;
          }
      }
      return withoutNulls;
  }