Java SE 8 是否有对或元组? [英] Does Java SE 8 have Pairs or Tuples?

查看:22
本文介绍了Java SE 8 是否有对或元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩 Java SE 8 中的惰性函数操作,我想 map 一个索引 i 到一对/元组 (i, value[i]),然后根据第二个 value[i] 元素进行 filter,最后只输出索引.

I am playing around with lazy functional operations in Java SE 8, and I want to map an index i to a pair / tuple (i, value[i]), then filter based on the second value[i] element, and finally output just the indices.

我还必须忍受这个吗:什么相当于 C++ 对 <L,R>在 Java 中? 在 lambda 和流的大胆新时代?

Must I still suffer this: What is the equivalent of the C++ Pair<L,R> in Java? in the bold new era of lambdas and streams?

更新:我提出了一个相当简化的示例,@dkatzel 在以下答案之一中提供了一个简洁的解决方案.然而,它确实泛化.因此,让我添加一个更通用的示例:

Update: I presented a rather simplified example, which has a neat solution offered by @dkatzel in one of the answers below. However, it does not generalize. Therefore, let me add a more general example:

package com.example.test;

import java.util.ArrayList;
import java.util.stream.IntStream;

public class Main {

  public static void main(String[] args) {
    boolean [][] directed_acyclic_graph = new boolean[][]{
        {false,  true, false,  true, false,  true},
        {false, false, false,  true, false,  true},
        {false, false, false,  true, false,  true},
        {false, false, false, false, false,  true},
        {false, false, false, false, false,  true},
        {false, false, false, false, false, false}
    };

    System.out.println(
        IntStream.range(0, directed_acyclic_graph.length)
        .parallel()
        .mapToLong(i -> IntStream.range(0, directed_acyclic_graph[i].length)
            .filter(j -> directed_acyclic_graph[j][i])
            .count()
        )
        .filter(n -> n == 0)
        .collect(() -> new ArrayList<Long>(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))
    );
  }

}

这给出了 [0, 0, 0]incorrect 输出,这对应于所有 的三列的 counts>假.我需要的是这三列的索引.正确的输出应该是 [0, 2, 4].我怎样才能得到这个结果?

This gives incorrect output of [0, 0, 0] which corresponds to the counts for the three columns that are all false. What I need are the indices of these three columns. The correct output should be [0, 2, 4]. How can I get this result?

推荐答案

更新: 这个答案是对原始问题的回应,Does Java SE 8 has Pairs or Tuples?em> (隐含地,如果不是,为什么不呢?) OP 已经用一个更完整的例子更新了这个问题,但它似乎可以在不使用任何类型的 Pair 结构的情况下解决.[来自 OP 的注意事项:这里是 另一个正确答案.]

UPDATE: This answer is in response to the original question, Does Java SE 8 have Pairs or Tuples? (And implicitly, if not, why not?) The OP has updated the question with a more complete example, but it seems like it can be solved without using any kind of Pair structure. [Note from OP: here is the other correct answer.]

简短的回答是否定的.你要么自己动手,要么引入实现它的几个库之一.

The short answer is no. You either have to roll your own or bring in one of the several libraries that implements it.

在 Java SE 中有一个 Pair 类被提议并被拒绝至少一次.请参阅 此讨论主题 之一OpenJDK 邮件列表.权衡并不明显.一方面,在其他库和应用程序代码中有许多 Pair 实现.这表明了一种需求,将这样的类添加到 Java SE 将增加重用和共享.另一方面,拥有一个 Pair 类增加了从 Pairs 和集合中创建复杂数据结构而不创建必要的类型和抽象的诱惑.(这是 Kevin Bourillion 的信息 从那个线程.)

Having a Pair class in Java SE was proposed and rejected at least once. See this discussion thread on one of the OpenJDK mailing lists. The tradeoffs are not obvious. On the one hand, there are many Pair implementations in other libraries and in application code. That demonstrates a need, and adding such a class to Java SE will increase reuse and sharing. On the other hand, having a Pair class adds to the temptation of creating complicated data structures out of Pairs and collections without creating the necessary types and abstractions. (That's a paraphrase of Kevin Bourillion's message from that thread.)

我建议每个人都阅读整个电子邮件线程.它非常有洞察力,没有火焰.这很有说服力.开始时我想,是的,Java SE 中应该有一个 Pair 类",但当线程结束时,我改变了主意.

I recommend everybody read that entire email thread. It's remarkably insightful and has no flamage. It's quite convincing. When it started I thought, "Yeah, there should be a Pair class in Java SE" but by the time the thread reached its end I had changed my mind.

但请注意,JavaFX 具有 javafx.util.Pair 类.JavaFX 的 API 与 Java SE API 分开发展.

Note however that JavaFX has the javafx.util.Pair class. JavaFX's APIs evolved separately from the Java SE APIs.

从链接的问题中可以看出 Java 中 C++ Pair 的等价物是什么? 围绕显然如此简单的 API 有相当大的设计空间.对象应该是不可变的吗?它们应该是可序列化的吗?它们应该具有可比性吗?这门课应该是最终的还是不是?这两个元素应该排序吗?它应该是接口还是类?为什么停在对?为什么不使用三元组、四元组或 N 元组?

As one can see from the linked question What is the equivalent of the C++ Pair in Java? there is quite a large design space surrounding what is apparently such a simple API. Should the objects be immutable? Should they be serializable? Should they be comparable? Should the class be final or not? Should the two elements be ordered? Should it be an interface or a class? Why stop at pairs? Why not triples, quads, or N-tuples?

当然,元素的命名是不可避免的:

And of course there is the inevitable naming bikeshed for the elements:

  • (a, b)
  • (第一,第二)
  • (左、右)
  • (汽车,cdr)
  • (foo, bar)
  • 等等

几乎没有提到的一个大问题是 Pairs 与原语的关系.如果您有一个 (int x, int y) 数据表示二维空间中的一个点,则将其表示为 Pair 会消耗 三个对象 而不是两个 32 位字.此外,这些对象必须驻留在堆上,并且会产生 GC 开销.

One big issue that has hardly been mentioned is the relationship of Pairs to primitives. If you have an (int x, int y) datum that represents a point in 2D space, representing this as Pair<Integer, Integer> consumes three objects instead of two 32-bit words. Furthermore, these objects must reside on the heap and will incur GC overhead.

很明显,就像 Streams 一样,Pairs 的原始特化是必不可少的.我们想看吗:

It would seem clear that, like Streams, it would be essential for there to be primitive specializations for Pairs. Do we want to see:

Pair
ObjIntPair
ObjLongPair
ObjDoublePair
IntObjPair
IntIntPair
IntLongPair
IntDoublePair
LongObjPair
LongIntPair
LongLongPair
LongDoublePair
DoubleObjPair
DoubleIntPair
DoubleLongPair
DoubleDoublePair

即使是 IntIntPair 仍然需要堆上的一个对象.

Even an IntIntPair would still require one object on the heap.

这些当然让人想起 Java SE 8 中 java.util.function 包中函数式接口的激增.如果您不想要臃肿的 API,您会选择哪些忽略?您也可以争辩说这还不够,还应该添加诸如 Boolean 的特化.

These are, of course, reminiscent of the proliferation of functional interfaces in the java.util.function package in Java SE 8. If you don't want a bloated API, which ones would you leave out? You could also argue that this isn't enough, and that specializations for, say, Boolean should be added as well.

我的感觉是,如果 Java 很久以前就添加了 Pair 类,它会很简单,甚至是简单化,而且它不会满足我们现在设想的许多用例.考虑一下,如果在 JDK 1.0 时间框架中添加了 Pair,它可能是可变的!(查看 java.util.Date.)人们会对此感到满意吗?我的猜测是,如果在 Java 中有一个 Pair 类,它会有点排序 - 不是真的有用,每个人仍然会滚动自己来满足他们的需求,外部库中会有各种 Pair 和 Tuple 实现,人们仍然会争论/讨论如何修复 Java 的 Pair 类.换句话说,就在我们今天所处的同一个地方.

My feeling is that if Java had added a Pair class long ago, it would have been simple, or even simplistic, and it wouldn't have satisfied many of the use cases we are envisioning now. Consider that if Pair had been added in the JDK 1.0 time frame, it probably would have been mutable! (Look at java.util.Date.) Would people have been happy with that? My guess is that if there were a Pair class in Java, it would be kinda-sort-not-really-useful and everybody will still be rolling their own to satisfy their needs, there would be various Pair and Tuple implementations in external libraries, and people would still be arguing/discussing about how to fix Java's Pair class. In other words, kind of in the same place we're at today.

与此同时,一些工作正在进行以解决基本问题,即 JVM(最终是 Java 语言)对 值类型的更好支持.请参阅此 价值观状态 文档.这是初步的推测性工作,它仅涵盖 JVM 角度的问题,但背后已经有相当多的思考.当然,不能保证这会进入 Java 9 或任何地方,但它确实显示了当前对该主题的思考方向.

Meanwhile, some work is going on to address the fundamental issue, which is better support in the JVM (and eventually the Java language) for value types. See this State of the Values document. This is preliminary, speculative work, and it covers only issues from the JVM perspective, but it already has a fair amount of thought behind it. Of course there are no guarantees that this will get into Java 9, or ever get in anywhere, but it does show the current direction of thinking on this topic.

这篇关于Java SE 8 是否有对或元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆