Skip to content

Instantly share code, notes, and snippets.

@ashikuzzaman-ar
Created April 11, 2021 06:30
Show Gist options
  • Save ashikuzzaman-ar/5a03aaf256b852f5d0f2b9a118ee7ba6 to your computer and use it in GitHub Desktop.
Save ashikuzzaman-ar/5a03aaf256b852f5d0f2b9a118ee7ba6 to your computer and use it in GitHub Desktop.
Question: you have an array of integers and an array of sort order. You have to sort input array according to that sort order. Those numbers don't belongs to order list will sort ascending order and will add at the last of the result. Example: Input: [2, 3, 8, 4, 3, 5, 2, 7, 6, 2, 3, 5, 4, 1] Order: [5, 2, 3] Output: [5, 5, 2, 2, 2, 3, 3, 3, 1, …
/*
Question: you have an array of integers and an array of sort order. You have to sort input array according
to that sort order. Those numbers don't belongs to order list will sort ascending order and will add at
the last of the result.
Example:
Input: [2, 3, 8, 4, 3, 5, 2, 7, 6, 2, 3, 5, 4, 1]
Order: [5, 2, 3]
Output: [5, 5, 2, 2, 2, 3, 3, 3, 1, 4, 4, 6, 7, 8]
*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) {
List<Integer> input = List.of(2, 3, 8, 4, 3, 5, 2, 7, 6, 2, 3, 5, 4, 1);
List<Integer> order = List.of(5, 2, 3);
List<Integer> result = new ArrayList<>();
order.forEach(o -> result.addAll(input.stream().filter(i -> i.equals(o)).collect(Collectors.toList())));
result.addAll(input.stream().filter(i -> !order.contains(i)).sorted().collect(Collectors.toList()));
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment