简体   繁体   中英

How can I convert Pair to 2 dimensional array in JAVA?

Is there a simpler approach by which I can convert Pair to 2 dimensional array?

Here is what I have tried:

public int[][] func() {
      List<Pair<Integer, Integer>> pairs = new ArrayList<>();

      //this is example value
      pairs.add(new Pair<>(1,2));
      pairs.add(new Pair<>(2,3));
      pairs.add(new Pair<>(3,4));

      //I want to make array same size of pair's
      int[][] arr = new int[pairs.size()][2];

      for(int i =0 ; i < pairs.size(); i++) {
          arr[i][0] = pairs.get(i).getKey();
          arr[i][1] = pairs.get(i).getValue();
      }

      return arr;
  }

With Stream s:

int[][] arr = pairs.stream()
                   .map(pair -> new int[] {pair.getKey(),pair.getValue()})
                   .toArray(int[][]::new);

BTW, instead of using a javafx Pair class, perhaps it would be better to use the more standard java.util.AbstractMap.SimpleEntry class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM