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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在Java中合并兩個(gè)流?

如何在Java中合并兩個(gè)流?

尚方寶劍之說 2021-10-20 11:08:42
假設(shè)我們有如下兩個(gè)流: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 將兩個(gè)流合并到 [13, 1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 14] (順序無關(guān)緊要) . 還是我們只能同時(shí)處理一個(gè)流?此外,如果這兩個(gè)流是對(duì)象流,如何在不覆蓋equals()和hashCode()方法的情況下只保留不同的對(duì)象?例如: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'}我們認(rèn)為兩個(gè)學(xué)生是相同的,當(dāng)他們no相同并且不考慮name(所以 May 和 Marry 是同一個(gè)人,因?yàn)樗麄兊臄?shù)字都是“1”)。我找到了這個(gè)distinct()方法,但是這個(gè)方法是基于Object#equals(). 如果我們不能覆蓋equals()的方法,我們?cè)撊绾魏喜tream1以及stream2到有沒有重復(fù)的項(xiàng)目一個(gè)流?
查看完整描述

3 回答

?
慕神8447489

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊

您可以使用 concat()

IntStream.concat(stream1, stream2)


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

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個(gè)贊

即“如何將兩個(gè) IntStream 合并為一個(gè)”。


你的另一個(gè)問題是“如何在Stream<T>不覆蓋equals()andhashCode()方法的情況下合并兩個(gè)?” 可以使用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項(xiàng)目都是不同的,但不使用覆蓋equals,hashcode正如您所提到的。


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

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊

對(duì)于第一個(gè)問題,您可以使用“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}


查看完整回答
反對(duì) 回復(fù) 2021-10-20
  • 3 回答
  • 0 關(guān)注
  • 349 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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