Java List Pair sorting and printing

July 23, 2017, at 7:09 PM
import javafx.util.Pair;
List<Pair> mPairs = new ArrayList<Pair>();
Scanner input = new Scanner(;
         for(int c =0; c < 3; c++) {
            String one =;
            String two =;
                int oneint  = Integer.parseInt(data1);
                Pair pair = new Pair(oneint,two);

The user inputs a value: for example - "30 apple" and "10 banana". This is stored using List. The last line code outputs it like this: [[30=apple, 10=banana]]

Now what I want to do is to output the data ascending without the first number and without the brackets, like this:



I have tried several different methods without succeeding.

Answer 1

First, make sure to utilize the generic types of Pair. Currently you're using a raw type, which can have unintuitive behavior at times. To do this, change Pair to Pair<Integer,String>.

There are many ways to sort and iterate lists. Here's a concise way to do it in Java 8 using Comparator.comparing along with a method reference, and then using Iterable#forEach along with a lambda expression.

List<Pair<Integer,String>> mPairs = new ArrayList<>();
Scanner input = new Scanner(;
for (int c = 0; c < 3; c++) {
    String one =;
    String two =;
    mPairs.add(new Pair<>(Integer.valueOf(one), two));
mPairs.forEach(p -> System.out.println(p.getValue()));

Ideone Demo

An equivalent way to write those last two lines without any Java 8 features would be:

Collections.sort(mPairs, new Comparator<Pair<Integer,String>>() {
    public int compare(Pair<Integer,String> p1, Pair<Integer,String> p2) {
        return p1.getKey().compareTo(p2.getKey());
for (Pair<Integer,String> p : mPairs) {
Rent Charter Buses Company
Using the Interval with Operators (RxJava)

Using the Interval with Operators (RxJava)

I need to make a network request every 1/3 seconds and wait 3 seconds before onComplete methodHow do I do that? my code below waits 3 seconds before emitting items, and it's not what I want

Hibernate relation one to one update query

Hibernate relation one to one update query

I have two tables which have a one-to-one relationship

How to put Arrays in 2 columns using Frame or JFrame [on hold]

How to put Arrays in 2 columns using Frame or JFrame [on hold]

Is there anyway to put this unsorted and sorted numbers in 2 columns using Frame or JFrameDont have idea on how to make flexible numbers of textfields on Frames