是否有任何选项可以通过其属性从 Set/HashSet 中检索元素

假设我有:


Set<MyObj> set = new HashSet<>();


set.add(new MyObj("myParam1","myParam2","myParam3"));

set.add(new MyObj("myParam11","myParam22","myParam33"));

set.add(new MyObj("myParam111","myParam222","myParam333"));.....


public class MyObj {

   private String p1;

   private String p2;

   private String p3;


   @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        MyObj myObj = (MyObj) o;

        return Objects.equals(getP1(), myObj.getP1()) &&

                Objects.equals(getP2(), myObj.getP2());

    }


    @Override

    public int hashCode() {

        return Objects.hash(getP1(), getP2());

    }


}

我想不创建新对象,通过检索元素 p1 & p2


示例:我得到 2 个字符串: "myParam1","myParam2"


我想要结果: MyObj("myParam1","myParam2","myParam3")


我不想要这个:


set.stream().filter(a->a.equals(new MyObj("myParam1","myParam2",null))).findFirst()

相反,我想要像地图(运行时 O(1))之类的东西,而不使用它。


斯蒂芬大帝
浏览 141回答 3
3回答

慕斯王

set.stream()&nbsp; &nbsp;.filter(x -> x.getMyParam1().equals("myParam1") && x.getMyParam2().equals("myParam2"))&nbsp; &nbsp;.findFirst();但是在findFirst这里想一下……您正在使用 a Set,所以它没有意义。为了更清楚地说明这一点:&nbsp; &nbsp; Set<String> set = new HashSet<>();&nbsp; &nbsp; set.add("hello");&nbsp; &nbsp; set.add("world");&nbsp; &nbsp; set.add("jug");&nbsp; &nbsp; System.out.println(set.stream().findFirst().get()); // world&nbsp; &nbsp; // add them&nbsp; &nbsp; IntStream.range(0, 100_000)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> "" + i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEachOrdered(set::add);&nbsp; &nbsp; // remove them immediatly after&nbsp; &nbsp; IntStream.range(0, 100_000)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> "" + i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEachOrdered(set::remove);&nbsp; &nbsp; System.out.println(set.stream().findFirst().get()); // hello

开心每一天1111

那么为什么不做某事。像这样在过滤器内部:a->&nbsp;"myParam1".equals(a.getP1())&nbsp;&&&nbsp;"myParam2".equals(a.getP2())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java