2017-12-12 8 views
-1

나는 List<Object>에 100 개의 개체가 들어 있다고 가정 해 봅시다. Java 8 (계층 라이브러리가없는)에서 이 1ObjectList<List<Object>>을 얻는 가장 좋은 방법은 무엇입니까?목록 목록으로 목록에 나열

+2

@birryree 당신은 회신하기 전에 게시물을 읽을 수는 자바 (8)는 것을 의미하지 않는다 언급해서, 그것은 Java8 – Moussi

+0

@Moussi을 했나요되어하시기 바랍니다 비 Java8 특정 답변이 적용되지 않습니다. – birryree

+0

@birryree는 고전 자바로 모든 것을 할 수 있지만 포스터는 java8 솔루션을 찾고 있습니다. – Moussi

답변

1

은 당신이 takeWhile를 사용하여 IntStream와 인덱스를 생성 할 수 있습니다 (당신이 했나요 당신이 어쨌든이를 넣어 without any tierce library를 게시) 자바 (9)에서

@Test 
public void givenList_whenParitioningIntoNSublists_thenCorrect() { 
    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8); 
    List<List<Integer>> subSets = Lists.partition(intList, 3); 

    List<Integer> lastPartition = subSets.get(2); 
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8); 
    assertThat(subSets.size(), equalTo(3)); 
    assertThat(lastPartition, equalTo(expectedLastPartition)); 
} 
2

외부 final 카운터가 필요하지만 작동하는 것 같습니다.

// Must be final (or implicitly final). 
    AtomicInteger n = new AtomicInteger(); 
    Map<String, List<Integer>> groups = IntStream.range(0, 100) 
      .boxed() 
      .collect(Collectors.groupingBy(
        // Group by n/10. 
        o -> String.valueOf(n.getAndIncrement()/10) 
        ) 
      ); 
+0

PrimitiveIterator.OfInt를 사용하여 AtomicInteger를 피할 수 있습니다. – richardstartin

+0

@richardstartin - 멋지다! 고마워, 나는 PrimitiveIterator를 보지 못했다. – OldCurmudgeon

1

내가 먼저 (귀하의 경우 10 개 요소) 척 크기를 가지고, 다음 목록 가서 그것의 덩어리를 취할 subList을 사용하십시오. 예컨대 :

List<List<Object>> subLists = IntStream 
    .range(0, (int) Math.ceil((double) list.size()/subListSize)) 
    .mapToObj(i -> new ArrayList<> 
         (list.subList(i * subListSize, (i + 1) * subListSize))) 
    .collect(Collectors.toList()); 

참고 : double 및 천장에 캐스팅이 subListSize 정확히 list.size()를 분할하지 않는 경우 정수 나누기를 방지하기 위해 아래이다.

1

구아바를 사용하여 다음 해당 인덱스는에서 하위 목록을 사용하여 더 간단합니다 원래 목록. 이 에 대한 객체의 목록을 작동합니다 :

private static final int BATCH_SIZE = 10; 

public void test(){ 
    List<List<Object>> batchedLists = split(generateTestObjects()); 
} 

public List<List<Object>> split(List<Object> objects) { 
    return IntStream.iterate(0, n -> n + BATCH_SIZE) 
      .takeWhile(n -> n < objects.size()) 
      .map(t -> objects.subList(t, Math.min(t + BATCH_SIZE, objects.size())) 
      .collect(Collectors.toList()); 
} 

public List<Object> generateTestObjects(){ 
    return IntStream.range(0, 100) 
      .boxed() 
      .collect(Collectors.toList()); 
}