2016-08-15 1 views
0

は、ここで私は、私はストリームとして、いくつかのpersonsを処理し、Iのようストリームが処理した要素の数を数えるには?

@Test 
    public void testPersonStreamToFile() throws Exception { 
    Person person1 = new Person(Collections.singletonList("key1"), Collections.singletonMap("person1", "key1")); 
    Person person2 = new Person(Collections.singletonList("key2"), Collections.singletonMap("person2", "key2")); 

    File file = temporaryFolder.newFile("personStream.txt"); 
    System.out.println(file.toString()); 

    List<Person> persons = Arrays.asList(person1, person2); 

    Stream<String> personStream = persons 
     .stream() 
     .map(WorkflowTest::mapToJsonString); 


    Files.write(Paths.get(file.toURI()), (Iterable<String>) personStream::iterator); 
    System.out.println("Done"); 
    } 

ようJSONに必要な をそれらを変換

class Person { 
    List<String> keys; 
    Map<String, String> attributes; 

    public Person(List<String> keys, Map<String, String> attributes) { 
     this.keys = keys; 
     this.attributes = attributes; 
    } 

    public List<String> getKeys() { 
     return keys; 
    } 

    public Map<String, String> getAttributes() { 
     return attributes; 
    } 
    } 

のように見える Personクラスを持っている私の例

ですストリームを処理し、私はプログラムhoの終わりまで私に言うCounterを保ちたい多くのpersonsJSONに変換されました。

どうすればStreamsでこれを達成できますか?

+4

カウンタを保持するために使用できる 'peek'メソッドがあります。 – mszymborski

+0

これはすべての単一の要素(いくつかの要素を除外する条件はありません)に起こる場合、 'stream'はその中の要素を返す' count() '関数を持っています。 –

+0

または、JSON変換メソッド内のいくつかのカウンタをインクリメントすることができます。 – shmosel

答えて

2

あなたはこのようpeek操作を使用することができます。

0

お試しforEach

与えられたストリームの要素をマッピングするだけなので、サイズはcountと同じになります(ストリーム処理が終わった後の端末操作)。しかし、特定の基準に基づいて要素をフィルタリングする場合は、後でforEachを使用して簿記を行うことができます。どうやって? mapToJsonStringがここに呼び出された回数を示します、あなたの操作counter.get()

AtomicInteger counter = new AtomicInteger(0); 

Stream<String> personStream = persons 
    .stream() 
    .map(WorkflowTest::mapToJsonString) 
    .peek(str -> counter.incrementAndGet()); 

public class StreamFilter { 
    public static void main(String[] args) { 
     final AtomicInteger count = new AtomicInteger(); 
     IntStream.of(1, 2, 3) 
     .filter(i -> i % 2 == 0) 
     .forEach(
       i -> { 
        // do something with the i, e.g. write to file 
        count.incrementAndGet(); // use return value 
       }); 
     System.out.println(count.intValue()); 
    } } 
関連する問題