Java List Pair sorting and printing

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

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:

banana

apple

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(System.in);
for (int c = 0; c < 3; c++) {
    String one = input.next();
    String two = input.next();
    mPairs.add(new Pair<>(Integer.valueOf(one), two));
}
mPairs.sort(Comparator.comparing(Pair::getKey));
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>>() {
    @Override
    public int compare(Pair<Integer,String> p1, Pair<Integer,String> p2) {
        return p1.getKey().compareTo(p2.getKey());
    }
});
for (Pair<Integer,String> p : mPairs) {
    System.out.println(p.getValue());
}
Rent Charter Buses Company
READ ALSO
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

446
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

313
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

346