는 HashMap에서 각 번호의 최대 발행 수를 얻기 <정수, 목록 <정수 >>

고 울리는 :

나는 다음과 같은 문제에 대한 해결책을 찾기 위해 보유하고있는 운동, 처리 봤는데 : 나는이

HashMap<Integer, List<Integer>>

나는리스트의의 발생의 최대 번호로의 HashMap에서 모든 목록의 각 요소를 포함하는 목록을 얻을 수 있습니다. 그래서 내 HashMap에 다음과 같은 항목을 가지고있다 가정하자 :

25, [30,30,2]

7, [2, 2, 2]

8, [8, 30]

각각의 숫자의 최대 발생이기 때문에, [2, 2, 2, 8, 30, 30]이 경우, 어떻게 든 다음과 같은 요소가있는 목록을 얻어야한다 :

  • (2)의 경우는 (값이 7 년) 3의
  • (8)의 경우는 (값 8의 1)의
  • (30)의 경우는 (25의 값에서) 2의

나는 그렇게 할 스트림을 사용하려고, 나는 다음과 같은 코드를 작성했습니다 :

map.entrySet()
            .stream()
            .map(Map.Entry::getValue)
            .collect(Collectors.toList());

이는 각각의 목록을 가져옵니다,하지만 내가 필요로하는 것은 언급 한 최대 횟수와 목록의 모든 요소를 ​​포함하는 하나 개의 목록을 얻을 수 있습니다. 요소의 순서는 전혀 문제가되지 않습니다.

당신은 몇 가지 설명을 필요로하는 경우에 저에게 문의하십시오.

사전에 도움을 주셔서 감사합니다.

안드레아스 :

이런 식으로 수를 :

static List<Integer> maxOccurrence(Map<Integer, List<Integer>> input) {
    return input.values().stream()
        .flatMap(list -> list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.maxBy(Comparator.naturalOrder()))))
        .entrySet().stream().sorted(Map.Entry.comparingByKey())
        .flatMap(e -> LongStream.range(0, e.getValue().get()).mapToObj(x -> e.getKey()))
        .collect(Collectors.toList());
}

테스트

System.out.println(maxOccurrence(Map.of(
        25, List.of(30, 30, 2),
        7, List.of(2, 2, 2),
        8, List.of(8, 30))));

산출

[2, 2, 2, 8, 30, 30]

설명

  1. 목록을 즉, 값을 스트림 :

    input.values().stream()
    
    [8, 30]
    [2, 2, 2]
    [30, 30, 2]
    
  2. 각 목록의 각 값의 발생을 개수 :

    .flatMap(list -> list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream())
    
    8=1
    30=1
    2=3
    30=2
    2=1
    
  3. 각 번호의 경우, 가장 높은 발생을 선택 :

    .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.maxBy(Comparator.naturalOrder()))))
    
    {8=1, 2=3, 30=2}
    
  4. 번호 (키)으로 분류하는 스트리밍 :

    .entrySet().stream().sorted(Map.Entry.comparingByKey())
    
    2=3
    8=1
    30=2
    
  5. 발생에 의해 각 숫자를 반복합니다 :

    .flatMap(e -> LongStream.range(0, e.getValue().get()).mapToObj(x -> e.getKey()))
    
    2
    2
    2
    8
    30
    30
    
  6. 결과와 목록을 작성 :

    .collect(Collectors.toList())
    
    [2, 2, 2, 8, 30, 30]
    

추천

출처http://43.154.161.224:23101/article/api/json?id=224869&siteId=1