How to sort a list of data classes by multiple columns in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {

    // Data class
    static class Item {
        int a;
        int b;
        String label;

        Item(int a, int b, String label) {
            this.a = a;
            this.b = b;
            this.label = label;
        }

        @Override
        public String toString() {
            return "(" + a + ", " + b + ", " + label + ")";
        }
    }

    // Create dataset
    static List<Item> makeData() {
        List<Item> data = new ArrayList<>();
        data.add(new Item(7, 2, "python"));
        data.add(new Item(8, 3, "c"));
        data.add(new Item(3, 5, "c++"));
        data.add(new Item(4, 1, "c#"));
        data.add(new Item(3, 2, "java"));
        data.add(new Item(7, 1, "go"));
        data.add(new Item(1, 2, "rust"));
        return data;
    }

    // Sort by column 0, then column 1
    static void sortData(List<Item> data) {
        data.sort(Comparator
                .comparingInt((Item x) -> x.a)
                .thenComparingInt(x -> x.b));
    }

    // Print all items
    static void printData(List<Item> data) {
        for (Item item : data) {
            System.out.println(item);
        }
    }

    // Find first item by label
    static Item findByLabel(List<Item> data, String label) {
        for (Item item : data) {
            if (item.label.equals(label)) {
                return item;
            }
        }
        return null;
    }

    // Filter by first column
    static List<Item> filterByA(List<Item> data, int value) {
        List<Item> result = new ArrayList<>();
        for (Item item : data) {
            if (item.a == value) {
                result.add(item);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Item> data = makeData();

        sortData(data);
        System.out.println("Sorted data:");
        printData(data);

        System.out.println();
        System.out.println("Searching for 'java':");
        Item found = findByLabel(data, "java");
        if (found != null) {
            System.out.println(found);
        }

        System.out.println();
        System.out.println("Filtering items where a == 7:");
        List<Item> filtered = filterByA(data, 7);
        printData(filtered);
    }
}




/*
run:

Sorted data:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)

Searching for 'java':
(3, 2, java)

Filtering items where a == 7:
(7, 1, go)
(7, 2, python)

*/

 



answered Jan 29 by avibootz

Related questions

...