2016-07-04 3 views
3

모든 null을 제거하려고 시도하지만 마지막 키의 treeSet이 null이면 해당 키는 그대로 유지됩니다. 그래서 그것은 null 인 경우 마지막 항목을 삭제하는 방법을 생각하고있었습니다. 이것은 treeMap이므로 tm.lastKey()를 사용하여 마지막 요소에 액세스 할 수 있다고 생각했지만 그 메서드는 존재하지 않는 것 같습니다. 그래서이 질문은 두 가지입니다. 첫째, 마지막 하나를 포함하여 모든 null을 삭제하는 방법이 있습니까? 두 번째는 .lastKey() 메서드가 어디에 있습니까?null 값을 사용하여 treeMap 항목 삭제

public class Timing { 
    private static Map<String, SortedSet> tm = new TreeMap<String, SortedSet>(); 

    public static Map manipulate() { 
     SortedSet ss = new TreeSet(); 
     ss.add("APPL"); 
     ss.add("VOD"); 
     ss.add("MSFT"); 

     tm.put("2019-09-18",null); 
     tm.put("2019-09-21",ss); 
     tm.put("2019-09-22", null); 
     tm.put("2019-09-20",ss); 
     tm.put("2019-09-19", null); 
     tm.put("2019-09-23",null); 

     return tm; 
    } 

    public static void printMap() { 
     for (String s: tm.keySet()) { 
      System.out.println(s + ": " + tm.get(s)); 
     } 
    } 

    // Will delete all but the last one 
    public static void deleteNull() { 
     Set set = tm.entrySet(); 
     Iterator i = set.iterator(); 
     Map.Entry me = (Map.Entry) i.next(); 
     // there is no tm.lastKey()?? 
     while(i.hasNext()) { 
      if (me.getValue() == null) { 
       i.remove(); 
      } 
      me = (Map.Entry) i.next(); 
     } 
    } 
} 
+0

원시 형식을 사용하지 마십시오. – shmosel

+0

'tm'은'Map <>'입니다. 당연히 'TreeMap'의 메소드는 그 위에 표시되지 않습니다. – Kayaman

+0

오 예 ... 올바른 –

답변

5

당신과 함께 deleteNull 방법을 대체 할 수있는지도에서 null의 값으로 모든 항목을 제거하려면

tm.values().removeIf(Objects::isNull); 
+0

이것은 정말 좋습니다. 덕분에 –

+0

매우 우아하고 – niceman

0

자바 TreeMaplastKey() 방법을 지정한다. 에 대해서는 Java-Doc에서 확인할 수 있습니다.

문제는지도에 실제 유형을 숨기고 있기 때문에 메서드에 액세스 할 수 없다는 것입니다. 당신은 여기에서 볼 수 있습니다이에서

private static Map<String, SortedSet> tm = new TreeMap<String, SortedSet>(); 

, 당신의 방법은 tmMap 객체 인 그는 lastKey() 방법이없는 것을 알고있다. MapTreeMap으로 변경하거나 메서드 내부에 캐스트를하면 작동합니다.

대안 1 :

private static TreeMap<String, SortedSet> tm = new TreeMap<String, SortedSet>(); 

대안 2 :

public String lastKey() { 
    if (tm instanceof TreeMap<?, ?>) { 
     return ((TreeMap<String, SortedSet>) tm).lastKey(); 
    } else { 
     // Error! 
    } 
} 
0

이 작업을 수행하는 가장 간단한 방법은 반복자가 끝난 후 반복자를 한 번 더 반복하면 다음과 같이됩니다.

while(i.hasNext()) { 
    if (me.getValue() == null) { 
     i.remove(); 
    } 
    me = (Map.Entry) i.next(); 
} 
if (me.getValue() == null) { 
    i.remove(); 
} 
    me = (Map.Entry) i.next(); 

이렇게하면 마지막 값을 잡을 수 있습니다.

그러나 맵을 인쇄 한 것과 비슷한 키 세트를 사용할 수 있습니다.

Set<String> keySet = tm.keySet(); 
for(int ndx = 0; ndx < keySet.size(); ndx++){ 
    String key = keySet.get(ndx); 
    if(tm.get(key) == null){ 
     tm.remove(key); 
    } 
} 
+0

일부 항목을 제거한 후 세트의 크기가 변경되지 않을까? 그래서 우리는 멀티 쓰레드 예외 또는 경계의 인덱스 아웃을 얻었을 것입니다. –

+0

좋은 시도하지만 절대 간단한 방법은 내 의견에 Modus의 대답입니다 :) – niceman