2016-08-11 6 views
3

내 질문자바 트리 맵 인쇄 값 설명

어떤 키 하나가

값 이상을 가진 내가 인쇄 할 맵 값을 인쇄하는 것은 아래 위를 기반으로 세부

static Map<Integer, Set<String>> myMap = new TreeMap<>(); 


Key value 
1  a 
     b 
     c 

2  d 

3  e 

4  f 
     g 
     h 

는 동안 1과 4를 인쇄하고 싶습니다. 2와 3을 생략해야합니다.

인쇄

myMap.entrySet().forEach((e) -> { 
       System.out.println(e.getKey()); 
       e.getValue().forEach((c) -> { 
        System.out.println(" " + c); 
       }); 
      }); 

답변

2

예를 들어 filter

myMap.entrySet().stream().filter(entry -> entry.getValue().size() > 1).forEach... 

, 적용 할 수 있는가? 이 몇 줄의하지만, 간결성이 반드시 미덕 아닌,

for (Entry<Integer, Set<String>> e : myMap.entrySet()) { 
    if (e.getValue().size() > 1) { 
    System.out.println(e.getKey()); 
    for (String s : e.getValue()) { 
     System.out.println(" " + s); 
    } 
    } 
} 

부여 : 표준 필수적 형식은 읽기가 모두 쓰기 쉽고 쉽다. 선명도가 가장 중요한 관심사입니다.

4

당신은이에 대한 스트림을 사용하는 특별한 이유가

public class Test { 

    public static void main(String[] args) { 
     Map<Integer, Set<String>> myMap = new TreeMap<>(); 
     Set<String> set1 = new HashSet<>(); 
     Set<String> set2 = new HashSet<>(); 
     Set<String> set3 = new HashSet<>(); 

     set1.add("1"); 
     set1.add("2"); 
     set1.add("3"); 

     set2.add("2"); 

     set3.add("1"); 
     set3.add("2"); 

     myMap.put(1, set1);//3 Elements 
     myMap.put(2, set2);//1 Element 
     myMap.put(3, set3);//2 Elements 

     myMap.entrySet().stream() 
      .filter(entry -> entry.getValue() != null) 
      .filter(entry -> entry.getValue().size() > 1) 
      .forEach(System.out::println); 
    } 

} 

출력

1=[1, 2, 3] 
3=[1, 2]