Home > OS >  How to sort array of objects based on order of another array
How to sort array of objects based on order of another array

Time:12-31

I have an ArrayList of Strings in a certain particular order

ArrayList<String> sortedkeys

And I have an unordered set of objects

Set<Skugroup> unsortedSet

Where SkuGroup contains a key to be used for sorting

Class SkuGroup {
   private String sortkey;
   private String name; 
}

I need to copy all the SkuGroup objects into a new array in the same order of sortedSkus, where the sortedkey value is the same as the SkuGroup->sortkey

How can I accomplish this?

CodePudding user response:

I believe the best way would be to store the set as a TreeSet, because it keeps its elements sorted by a given comparator. To make it easier, here we can implement interface Comparable on the SkuGroup class.

class SkuGroup implements Comparable<SkuGroup> {
    private String sortKey;
    private String name;

    public String getSortKey() {
        return sortKey;
    }

    public int compareTo(SkuGroup s1) {
        return this.sortKey.trim().compareTo(s1.getSortKey().trim());
    }
}
ArrayList<String> sortedKeys = new ArrayList<>();

Set<SkuGroup> skuSet = new TreeSet<>();

/** add items to skuSet **/

I need to copy all the SkuGroup objects into a new array in the same order of sortedSkus, where the sortedkey value is the same as the SkuGroup->sortkey

I assume you mean you want to transfer just the sortKey, and not the entire object because of the type on the ArrayList.

skuSet.stream().forEach(item -> sortedKeys.add(item.getSortKey()));

CodePudding user response:

import java.util.*;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        System.out.println("Expected order: c -> b -> a -> d");
        List<String> sortedkeys = Arrays.asList("c", "b", "a", "d");

        // Construct unsorted set (of course a Set has no order);
        System.out.println("Unsorted order: a -> b -> c -> d");
        Set<SkuGroup> unsortedSet = new HashSet<>(Arrays.asList(
                new SkuGroup("a", "name_a"),
                new SkuGroup("b", "name_b"),
                new SkuGroup("c", "name_c"),
                new SkuGroup("d", "name_d")));

        List<SkuGroup> sortedSkuGroups = sortedkeys.stream()
                .map(key -> unsortedSet.stream()
                        .filter(skuGroup -> skuGroup.getSortKey().equals(key))
                        .findFirst()
                        .get()
                ).collect(Collectors.toList());
        System.out.println("Sorted order: "   sortedSkuGroups);

        // In case if you need to convert this into Array:
        SkuGroup[] sortedSkuGroupArray = sortedSkuGroups.stream().toArray(SkuGroup[]::new);
        System.out.println("Sorted order in Array: "   Arrays.toString(sortedSkuGroupArray));
    }
}

class SkuGroup {
    private String sortKey;
    private String name;

    public SkuGroup(String sortKey, String name) {
        this.sortKey = sortKey;
        this.name = name;
    }

    public String getSortKey() {
        return sortKey;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "{'"   sortKey   '\''   ":'"   name   "\'}";
    }
}

Result:

> Task :Test.main()
Expected order: c -> b -> a -> d
Unsorted order: a -> b -> c -> d
Sorted order: [{'c':'name_c'}, {'b':'name_b'}, {'a':'name_a'}, {'d':'name_d'}]
Sorted order in Array: [{'c':'name_c'}, {'b':'name_b'}, {'a':'name_a'}, {'d':'name_d'}]
  • Related