排序整数列表。开头

时间:2015-12-16 06:37:38

标签: java list sorting arraylist

我有5个元素的随机列表,如[14,9,7,7,14]或[2,7,11,7,8],我想对它们进行排序。首先我打电话:

Collections.sort(List);

它给我这样的列表:[7,7,9,14,14]和[2,7,7,8,11]。当列表的相同元素位于我的列表的第一个位置时,我想实现这种情况。像:

排序后的[7,7,9,14,14]:[7,7,14,14,9]

排序后的

[2,7,7,8,11]:[7,7,8,11]

[4,8,8,8,9]排序后:[8,8,8,4,9]

[5,8,8,8,8]排序后:[8,8,8,8,5]

我如何实现这一目标?有没有好办法呢?

2 个答案:

答案 0 :(得分:3)

  public class Sort {

  public static void main(String[] args) {
    int[] arr = new int[]{14, 9, 7, 7, 14};
    Map<Integer, Temp> map = new HashMap<>();

    for(int i: arr){
      Temp t = map.getOrDefault(i, new Temp(i));
      map.put(i,t.increment()); 
    }
    List<Temp> l = new ArrayList<>(map.values());
    Collections.sort(l, (o,t)-> o.count ==t.count ?o.value - t.value : t.count-o.count);

    List<Integer> finalList = new ArrayList<>() ;
    for(Temp t: l){
       for(int i=0;i<t.count;i++){
         finalList.add(t.value);
       }
    }
    System.out.println(finalList);
  }

  static class Temp{
    int value, count;
    public Temp(int i) {
      value=i;
    }
    public Temp increment(){
      count++;
      return this;
    }

  }

试用Java-8方式

public class Sort {

  public static void main(String[] args) {
    int[] arr = new int[] { 14, 9, 7, 7, 14 };
    Map<Integer, Temp> map = new HashMap<>();

    for (int i : arr) {
      Temp t = map.getOrDefault(i, new Temp(i));
      map.put(i, t.increment());
    }

    List<Integer> collect = map.values().stream()
      .sorted((o, t) -> o.count == t.count ? o.value - t.value : t.count - o.count)
      .map(t -> IntStream.range(0, t.count).map(i -> t.value)
      .collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll))
      .flatMap(ll -> ll.stream())
      .collect(Collectors.toList());
    System.out.println(collect);

  }

  static class Temp {
    int value, count;
    public Temp(int i) {
      value = i;
    }
    public Temp increment() {
      count++;
      return this;
    }
  }
}

答案 1 :(得分:1)

遵循ajb建议,这里是Java 8代码,正如他所说的花式比较器,

  public static int[] funSort(int[] array) {
    HashMap<Integer, Integer> map = new HashMap<>();
    for(int value: array) {
      map.merge(value, 1, Integer::sum);
    }
    return map.entrySet().stream()
      .sorted(Map.Entry.<Integer, Integer>comparingByValue()
          .thenComparing(Map.Entry.comparingByKey())
          .reversed())
      .flatMap(e -> Collections.nCopies(e.getValue(), e.getKey()).stream())
      .mapToInt(Integer::intValue)
      .toArray();
  }