List集合中把其中一個元素 調整到集合的第一位

要求:如今想把集合中的某個元素,放到該集合的第一個位置,可是其餘元素的順序不須要管。spa

方法:須要遍歷集合,找到這個元素在集合中的位置,而後使用Collections.swap(list,o,i) (O:爲元素目前所在位置,i:爲要放置的位置)方法來進行元素調換code

public static void main(String[] args) {
        List<String> test = Lists.newArrayList();
        test.add("test1");
        test.add("test2");
        test.add("test3");

        System.out.println("更改前:" + JSON.toJSONString(test));

        Collections.swap(test, 1, 0);

        System.out.println("更改後:" + JSON.toJSONString(test));
    }

 

結果:blog

相關文章
相關標籤/搜索