2017-07-03 48 views
-1

假設我有以下結構:(以JSON爲例)與依賴於其他項目在Java stucture刪除條目

... 
{event: Web, action:Video, timestamp:1320}, 
{event: Web, action:Play, timestamp: 1320}, 
{event: Web, action:Download, timestamp: 1320}, 
{event: Web, action:Play, timestamp: 1321} 
... 

現在我想重複的結構,並刪除與「行動的所有行:播放「,其中的動作是:下載具有相同的時間戳。

那麼結果會是這樣的:

... 
{event: Web, action:Video, timestamp:1320}, 
{event: Web, action:Download, timestamp: 1320}, 
{event: Web, action:Play, timestamp: 1321} 
... 

我不確定,我是誰應該在Java中實現這一點。我的問題是在這裏:我應該使用type(List,Map,...)和Algo來解決這個問題嗎?

+0

你有什麼試過的?這些「結構」到底是什麼?他們是上課嗎? – UnholySheep

+0

這就是問題,我應該在那裏使用哪種結構? – domi13

+0

我只有一個建議:邊做邊學。如果你不知道如何從這個問題開始,那麼首先找到一個更容易解決的問題。 – EasterBunnyBugSmasher

回答

0

您需要定義一個變量一類像時間戳

下面是一個例子:

static class MediaPlayer{ 
     String event; 
     String action; 
     int timestamp; 
     public MediaPlayer(String event, String action,int timestamp){ 
      this.event=event; 
      this.action=action; 
      this.timestamp=timestamp; 
     } 
     public String getEvent(){ 
      return event; 
     } 
     public String getAction(){ 
      return action; 
     } 
     public int getTimeStamp(){ 
      return timestamp; 
     } 
    } 

然後在主要的類名對象您可以創建一個列表。遍歷它們並使用removeAll()方法刪除它們。

public static void main(String args[]){ 

     List<MediaPlayer> mp=new ArrayList<>(); 
     List<MediaPlayer> remove=new ArrayList<>();//I have made this for demostration purpose that you could even collect these objects somewhere and do something with them! 

     mp.add(new MediaPlayer("web","Video",1320)); 
     mp.add(new MediaPlayer("web","Play",1320)); 
     mp.add(new MediaPlayer("web","Download",1320)); 
     mp.add(new MediaPlayer("web","Play",1321)); 

     mp.forEach((it)->{ 
      System.out.println("Event: "+it.getEvent()+" Action: "+it.getAction()+" TimeStamp: "+it.getTimeStamp()); 
     }); 

     Iterator<MediaPlayer> iter = mp.iterator(); 
     Iterator<MediaPlayer> iter1 = mp.iterator(); 
     for(MediaPlayer it:mp){ 
      for(MediaPlayer itr:mp){ 
       if(it.getAction().equals("Download") && it.getTimeStamp()==itr.getTimeStamp() && itr.getAction().equals("Play")){ 
        remove.add(itr);// I add the objects to be removed in remove list first. This way I will even have the list of deleted objects 
       } 
      } 
     } 
     mp.removeAll(remove);//Then finally I remove them from main list 

     System.out.println("\n"); 
     mp.forEach((it)->{ 
      System.out.println("Event: "+it.getEvent()+" Action: "+it.getAction()+" TimeStamp: "+it.getTimeStamp()); 
     }); 
} 
相關問題