第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Java中合并兩個流?

如何在Java中合并兩個流?

尚方寶劍之說 2021-10-20 11:08:42
假設(shè)我們有如下兩個流:IntStream stream1 = Arrays.stream(new int[] {13, 1, 3, 5, 7, 9});IntStream stream2 = Arrays.stream(new int[] {1, 2, 6, 14, 8, 10, 12});stream1.merge(stream2); // some method which is used to merge two streams.有沒有什么方便的方法可以使用 Java 8 流 API 將兩個流合并到 [13, 1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 14] (順序無關(guān)緊要) . 還是我們只能同時處理一個流?此外,如果這兩個流是對象流,如何在不覆蓋equals()和hashCode()方法的情況下只保留不同的對象?例如:public class Student {    private String no;    private String name;}Student s1 = new Student("1", "May");Student s2 = new Student("2", "Bob");Student s3 = new Student("1", "Marry");Stream<Student> stream1 = Stream.of(s1, s2);Stream<Student> stream2 = Stream.of(s2, s3);stream1.merge(stream2);  // should return Student{no='1', name='May'} Student{no='2', name='Bob'}我們認為兩個學(xué)生是相同的,當(dāng)他們no相同并且不考慮name(所以 May 和 Marry 是同一個人,因為他們的數(shù)字都是“1”)。我找到了這個distinct()方法,但是這個方法是基于Object#equals(). 如果我們不能覆蓋equals()的方法,我們該如何合并stream1以及stream2到有沒有重復(fù)的項目一個流?
查看完整描述

3 回答

?
慕神8447489

TA貢獻1780條經(jīng)驗 獲得超1個贊

您可以使用 concat()

IntStream.concat(stream1, stream2)


查看完整回答
反對 回復(fù) 2021-10-20
?
DIEA

TA貢獻1820條經(jīng)驗 獲得超3個贊

即“如何將兩個 IntStream 合并為一個”。


你的另一個問題是“如何在Stream<T>不覆蓋equals()andhashCode()方法的情況下合并兩個?” 可以使用toMap收集器完成,即假設(shè)您不希望結(jié)果為Stream<T>. 例子:


Stream.concat(stream1, stream2)

      .collect(Collectors.toMap(Student::getNo, 

               Function.identity(), 

               (l, r) -> l, 

               LinkedHashMap::new)

      ).values();

如果你想要結(jié)果,Stream<T>那么你可以這樣做:


 Stream.concat(stream1, stream2)

       .collect(Collectors.collectingAndThen(

               Collectors.toMap(Student::getNo,

                    Function.identity(),

                    (l, r) -> l,

                    LinkedHashMap::new), 

                    f -> f.values().stream()));

這可能不像它那樣有效,但它是另一種返回 a 的方法,Stream<T>其中T項目都是不同的,但不使用覆蓋equals,hashcode正如您所提到的。


查看完整回答
反對 回復(fù) 2021-10-20
?
交互式愛情

TA貢獻1712條經(jīng)驗 獲得超3個贊

對于第一個問題,您可以使用“flatMap”


    IntStream stream1 = Arrays.stream(new int[] {13, 1, 3, 5, 7, 9});

    IntStream stream2 = Arrays.stream(new int[] {1, 2, 6, 14, 8, 10, 12});


    List<Integer> result = Stream.of(stream1, stream2).flatMap(IntStream::boxed)

            .collect(Collectors.toList());

    //result={13, 1, 3, 5, 7, 9, 1, 2, 6, 14, 8, 10, 12}


查看完整回答
反對 回復(fù) 2021-10-20
  • 3 回答
  • 0 關(guān)注
  • 357 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號