Java SE 8에 페어 또는 튜플이 있습니까?
Java SE 8에서 게으른 기능 연산으로 놀고 있으며 두 번째 요소 를 기반으로 한 쌍 / 튜플에 map색인 i을 만들고 마지막으로 색인 만 출력 하려고합니다 .(i, value[i])filtervalue[i]
여전히이 문제를 겪어야합니까 : Java에서 C ++ Pair <L, R>과 동등한 것은 무엇입니까? 람다와 개울의 대담한 새로운 시대에?
업데이트 : 나는 아래 답변 중 하나에서 @dkatzel이 제공하는 깔끔한 솔루션을 가진 다소 단순화 된 예를 제시했습니다. 그러나 일반화 되지는 않습니다 . 따라서보다 일반적인 예를 추가하겠습니다.
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]false[0, 2, 4]
업데이트 : 이 답변은 원래 질문에 대한 답변입니다 . Java SE 8에 페어 또는 튜플이 있습니까? (그리고 내재적으로, 그렇지 않은 경우 왜 그렇지 않습니까?) OP는 더 완전한 예제로 질문을 업데이트했지만 어떤 종류의 쌍 구조를 사용하지 않고도 해결할 수있는 것처럼 보입니다. [OP의 메모 : 여기 에 다른 정답이 있습니다.]
짧은 대답은 '아니요'입니다. 자신의 롤을 구현하거나이를 구현하는 여러 라이브러리 중 하나를 가져와야합니다.
PairJava SE에서 클래스를 갖는 것이 제안되고 적어도 한 번 거부되었습니다. OpenJDK 메일 링리스트 중 하나 에서이 토론 스레드 를 참조하십시오 . 트레이드 오프는 분명하지 않습니다. 한편으로 다른 라이브러리와 응용 프로그램 코드에는 많은 Pair 구현이 있습니다. 이는 필요를 보여 주며, 이러한 클래스를 Java SE에 추가하면 재사용 및 공유가 증가합니다. 반면에 Pair 클래스를 사용하면 필요한 유형과 추상화를 만들지 않고 Pairs 및 Collections에서 복잡한 데이터 구조를 만드는 유혹을 더할 수 있습니다. (그것이 스레드에서 보낸 Kevin Bourillion의 메시지에 대한 역설입니다 .)
나는 모든 사람이 그 전체 이메일 스레드를 읽는 것이 좋습니다. 놀랍도록 통찰력이 있으며 흠이 없습니다. 꽤 설득력이 있습니다. 처음 시작했을 때, "예, Java SE에는 Pair 클래스가 있어야합니다"라고 생각했지만 스레드가 끝날 무렵에는 마음이 바뀌 었습니다.
그러나 JavaFX에는 javafx.util.Pair 클래스가 있습니다. JavaFX의 API는 Java SE API와 별도로 발전했습니다.
링크 된 질문에서 알 수 있듯이 Java의 C ++ 쌍에 해당하는 것은 무엇입니까? 이러한 단순한 API를 둘러싼 상당히 큰 디자인 공간이 있습니다. 객체가 불변이어야합니까? 그것들은 직렬화 가능해야합니까? 비교할 수 있어야합니까? 수업은 마지막이어야합니까? 두 요소를 주문해야합니까? 인터페이스 또는 클래스 여야합니까? 왜 쌍에서 멈춰? 트리플, 쿼드 또는 N 튜플이 아닌 이유는 무엇입니까?
물론 요소의 피할 수없는 이름 지정이 있습니다.
- (a, b)
- (첫번째 두번째)
- (왼쪽 오른쪽)
- (차, cdr)
- (푸, 바)
- 기타
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.
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
Even an IntIntPair would still require one object on the heap.
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.
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.
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.
You can have a look on these built-in classes :
Sadly, Java 8 did not introduce pairs or tuples. You can always use org.apache.commons.lang3.tuple of course (which personally I do use in combination with Java 8) or you can create your own wrappers. Or use Maps. Or stuff like that, as is explained in the accepted answer to that question you linked to.
It appears that the full example can be solved without the use of any kind of Pair structure. The key is to filter on the column indexes, with the predicate checking the entire column, instead of mapping the column indexes to the number of false entries in that column.
The code that does this is here:
    System.out.println(
        IntStream.range(0, acyclic_graph.length)
            .filter(i -> IntStream.range(0, acyclic_graph.length)
                                  .noneMatch(j -> acyclic_graph[j][i]))
            .boxed()
            .collect(toList()));
This results in output of [0, 2, 4] which is I think the correct result requested by the OP.
Also note the boxed() operation that boxes the int values into Integer objects. This enables one to use the pre-existing toList() collector instead having to write out collector functions that do the boxing themselves.
Since you only care about the indexes, you don't need to map to tuples at all. Why not just write a filter that uses the looks up elements in your array?
     int[] value =  ...
IntStream.range(0, value.length)
            .filter(i -> value[i] > 30)  //or whatever filter you want
            .forEach(i -> System.out.println(i));
Yes.
Map.Entry can be used as a Pair. 
Unfortunately it does not help with Java 8 streams as the problem is that even though lambdas can take multiple arguments, the Java language only allows for returning a single value (object or primitive type). This implies that whenever you have a stream you end up with being passed a single object from the previous operation. This is a lack in the Java language, because if multiple return values was supported AND streams supported them we could have much nicer non-trivial tasks done by streams.
Until then, there is only little use.
EDIT 2018-02-12: While working on a project I wrote a helper class which helps handling the special case of having an identifier earlier in the stream you need at a later time but the stream part in between does not know about it. Until I get around to release it on its own it is available at IdValue.java with a unit test at IdValueTest.java
Vavr (formerly called Javaslang) (http://www.vavr.io) provides tuples (til size of 8) as well. Here is the javadoc: https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/Tuple.html.
This is a simple example:
Tuple2<Integer, String> entry = Tuple.of(1, "A");
Integer key = entry._1;
String value = entry._2;
Why JDK itself did not come with a simple kind of tuples til now is a mystery to me. Writing wrapper classes seems to be an every day business.
Since Java 9, you can create instances of Map.Entry easier than before:
Entry<Integer, String> pair = Map.entry(1, "a");
Map.entry returns an unmodifiable Entry and forbids nulls.
Eclipse Collections has Pair and all combinations of primitive/object Pairs (for all eight primitives). 
The Tuples factory can create instances of Pair, and the PrimitiveTuples factory can be used to create all combinations of primitive/object pairs.
We added these before Java 8 was released. They were useful to implement key/value Iterators for our primitive maps, which we also support in all primitive/object combinations.
If you're willing to add the extra library overhead, you can use Stuart's accepted solution and collect the results into a primitive IntList to avoid boxing. We added new methods in Eclipse Collections 9.0 to allow for Int/Long/Double collections to be created from Int/Long/Double Streams.
IntList list = IntLists.mutable.withAll(intStream);
Note: I am a committer for Eclipse Collections.
I'm not expert in java, just a student, but i made my workaround to simulate the tuples like in python:
class C1 { 
    String name; int X,Y;
    C1(List l){name = ""+l.get(0); X=(int)l.get(1); Y=(int)l.get(2);}
}
class MyClass{
    List l2= List.of(List.of("a",7,9), List.of("b",8,4), List.of("c",3,6)); //here
    List l3=new ArrayList();
    for (Object li: l2) l3.add(new C1((List)li));
}
Hope this helps.
참고URL : https://stackoverflow.com/questions/24328679/does-java-se-8-have-pairs-or-tuples
'Programming' 카테고리의 다른 글
| Path.Combine이 Path.DirectorySeparatorChar로 시작하는 파일 이름을 올바르게 연결하지 않는 이유는 무엇입니까? (0) | 2020.05.24 | 
|---|---|
| C # 메서드 이름에 "Try"는 언제 사용됩니까? (0) | 2020.05.24 | 
| BOM이없는 UTF-8 (0) | 2020.05.24 | 
| C ++에서 열거 형을 선언 할 때 typedef를 사용하는 이유는 무엇입니까? (0) | 2020.05.24 | 
| 배치 파일에 파일이 있는지 확인하는 방법은 무엇입니까? (0) | 2020.05.24 |