Java Lambda流Distinct()在任意键上?

我经常遇到Java lambda表达式的问题,当我想对对象的任意属性或方法上的stream()进行区分()时,我想保留该对象而不是将其映射到该属性或方法上。我开始按照这里的讨论来创建容器,但是我开始做得足够好,以至于变得烦人并创建了许多样板课程。


我将这个Pairing类放在一起,该类包含两种类型的两个对象,并允许您指定左,右或两个对象的键控。我的问题是……在某种类型的关键供应商上,实际上没有内置的lambda流函数可对distinct()吗?那真的会让我感到惊讶。如果不是,此类将可靠地实现该功能吗?


这就是它的称呼


BigDecimal totalShare = orders.stream().map(c -> Pairing.keyLeft(c.getCompany().getId(), c.getShare())).distinct().map(Pairing::getRightItem).reduce(BigDecimal.ZERO, (x,y) -> x.add(y));

这是配对课程


    public final class Pairing<X,Y>  {

           private final X item1;

           private final Y item2;

           private final KeySetup keySetup;


           private static enum KeySetup {LEFT,RIGHT,BOTH};


           private Pairing(X item1, Y item2, KeySetup keySetup) {

                  this.item1 = item1;

                  this.item2 = item2;

                  this.keySetup = keySetup;

           }

           public X getLeftItem() { 

                  return item1;

           }

           public Y getRightItem() { 

                  return item2;

           }


           public static <X,Y> Pairing<X,Y> keyLeft(X item1, Y item2) { 

                  return new Pairing<X,Y>(item1, item2, KeySetup.LEFT);

           }


           public static <X,Y> Pairing<X,Y> keyRight(X item1, Y item2) { 

                  return new Pairing<X,Y>(item1, item2, KeySetup.RIGHT);

           }

           public static <X,Y> Pairing<X,Y> keyBoth(X item1, Y item2) { 

                  return new Pairing<X,Y>(item1, item2, KeySetup.BOTH);

           }

           public static <X,Y> Pairing<X,Y> forItems(X item1, Y item2) { 

                  return keyBoth(item1, item2);

           }

           }


    }


慕运维8079593
浏览 1131回答 3
3回答

海绵宝宝撒

在下面测试了Stuart的功能,它看起来很棒。下面的操作在每个字符串的第一个字母上有所区别。我要弄清楚的唯一部分是ConcurrentHashMap如何仅维护整个流的一个实例public class DistinctByKey {&nbsp; &nbsp; public static <T> Predicate<T> distinctByKey(Function<? super T,Object> keyExtractor) {&nbsp; &nbsp; &nbsp; &nbsp; Map<Object,Boolean> seen = new ConcurrentHashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; final ImmutableList<String> arpts = ImmutableList.of("ABQ","ALB","CHI","CUN","PHX","PUJ","BWI");&nbsp; &nbsp; &nbsp; &nbsp; arpts.stream().filter(distinctByKey(f -> f.substring(0,1))).forEach(s -> System.out.println(s));&nbsp; &nbsp; }输出是...ABQCHIPHXBWI

四季花海

您或多或少必须要做类似的事情&nbsp;elements.stream()&nbsp; &nbsp; .collect(Collectors.toMap(&nbsp; &nbsp; &nbsp; &nbsp; obj -> extractKey(obj),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; obj -> obj,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;(first, second) -> first&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// pick the first if multiple values have the same key&nbsp; &nbsp; &nbsp; &nbsp;)).values().stream();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java