java---随机打乱集合

287 阅读1分钟
package com.example.demo.dto;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


@Slf4j
class UserDtosTest {

public static String mockS() {
    return "[\n" +
            "    {\n" +
            "      "name": "bwf",\n" +
            "      "age": 12\n" +
            "    },\n" +
            "    {\n" +
            "      "name": "wmy",\n" +
            "      "age": 40\n" +
            "    },\n" +
            "    {\n" +
            "      "name": "xiaoming",\n" +
            "      "age": 28\n" +
            "    },\n" +
            "    {\n" +
            "      "name": "zhangsan",\n" +
            "      "age": 50\n" +
            "    }\n" +
            "  ]";
}

public static void main(String[] args) throws JsonProcessingException {
    List<UserDTO> source = JSON.parseArray(mockS(), UserDTO.class);
    // 生成索引
    List<Integer> indexs = IntStream.range(0, source.size()).boxed().collect(Collectors.toList());
    // 打乱索引
    Collections.shuffle(indexs);
    List<UserDTO> target = indexs.stream().map(index -> source.get(index)).collect(Collectors.toList());
    log.info("target:{}", JSON.toJSONString(target));
  }
}
package com.example.demo.dto;

import lombok.Data;

@Data
public class UserDTO {

    private String name;

    private String age;

}