Sorting List of Objects by their int variable

前端 未结 2 1564
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 05:03

I have a class (ClassOne) that has a list of instanced Classes(Process) and i\'m trying to figure out how to sort them based on their priority int.

public class C         


        
相关标签:
2条回答
  • 2021-01-28 05:19

    with java 8+ you can try this code below:

    import java.util.*;
    import java.util.stream.Collectors;
    public static void InsertionSort()
    {
        System.out.println(processList.get(0).name);
        System.out.println(processList.get(1).name);
        System.out.println(processList.get(2).name);
        
        processList=processList.stream()
        .sorted((o1,o2)->{return o1.priority-o2.priority;})
        .collect(Collectors.toList());
        
        System.out.println(processList.get(0).name);
        System.out.println(processList.get(1).name);
        System.out.println(processList.get(2).name);
    }
    
    0 讨论(0)
  • 2021-01-28 05:25

    Use List#set to set an element at an index.

    processList.get(j+1).priority = processList.get(j).priority; 
    

    becomes

     processList.set(j+1, processList.get(j));
    

    And

    processList.get(j + 1).priority = key; 
    

    becomes

    processList.set(j+1, processList.get(i));
    
    0 讨论(0)
提交回复
热议问题