List集合操作

查询两个List的差集

  • 简单类型
/**
 * 差集
 * 求List1中有的但是List2中没有的元素
 */
public static List<String> diffList(List<String> list1, List<String> list2) {
    Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
    return list1.parallelStream().filter(str->{
        return !tempMap.containsKey(str);
    }).collect(Collectors.toList());
}
  • 对象类型
public static void main(String[] args) {
    List<Student> list1 = new ArrayList<>();
    list1.add(new Student("name1","1001"));
    list1.add(new Student("name2","1002"));
    list1.add(new Student("name3","1003"));

    List<Student> list2 = new ArrayList<>();
    list2.add(new Student("name3","1003"));
    list2.add(new Student("name4","1004"));

    Set<Student> list1Set = new HashSet<>(list1);
    Set<Student> list2Set = new HashSet<>(list2);
    // 差集 (list1 - list2)
    List<Student> reduce1 = list1.stream().filter(item -> !list2Set.contains(item)).collect(Collectors.toList());
    reduce1.parallelStream().forEach(System.out::println);
    // 差集 (list2 - list1)
    List<Student> reduce2 = list2.stream().filter(item -> !list1Set.contains(item)).collect(Collectors.toList());
    reduce2.parallelStream().forEach(System.out::println);
}

static class Student {
    /**
     * 姓名
     */
    private String name;

    /**
     * 学号 唯一值
     */
    private String code;

    public Student(String name, String code) {
        this.name = name;
        this.code = code;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Student)) {
            return false;
        }
        Student student = (Student) o;
        return code.equals(student.getCode());
    }

    @Override
    public int hashCode() {
        return Objects.hash(code);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", code='" + code + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public String getCode() {
        return code;
    }
}

 查询两个List的交集

  • 简单类型
public static List<String> interpList(List<String> list1, List<String> list2) {
    Set<String> list2Set = new HashSet<>(list2);
    return list1.stream().filter(list2Set::contains).collect(Collectors.toList());
}
  • 对象类型
public static void main(String[] args) {
    List<Student> list1 = new ArrayList<>();
    list1.add(new Student("name1","1001"));
    list1.add(new Student("name2","1002"));
    list1.add(new Student("name3","1003"));

    List<Student> list2 = new ArrayList<>();
    list2.add(new Student("name3","1003"));
    list2.add(new Student("name4","1004"));

    Set<Student> list1Set = new HashSet<>(list1);
    Set<Student> list2Set = new HashSet<>(list2);
    // 交集
    List<Student> interp = list1.stream().filter(list2Set::contains).collect(Collectors.toList());
    interp.parallelStream().forEach(System.out::println);
}

List合并

public static List<Map> addList(List<Map> list1, List<Map> list2){
    return Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList());
}

 List去重

public static List<String> delList(List<String> varList){
    return varList.stream().distinct().collect(Collectors.toList());
}

字符串按特定分隔符转换为List

public static List<Long> strToList(String ids){
    List<Long> idList = Arrays.asList(ids.split(",")).stream().distinct().map(s -> Long.parseLong(s.trim())).collect( Collectors.toList() );
    return idList;
}

List截取一段数据

public static List<String> subList(List<String> list, Integer formIndex, Integer toIndex){
    return list.subList(formIndex,toIndex);
}

但存在如下问题,如对原list在做操作,就会出现异常。

即对list截取后,就只能读取原来的list,不能进行“写”操作。


List内字段下划线转驼峰

  • 实体集合

现有实体ColumnDto如下:

/**
 * 列的属性
 */
@Data
public class ColumnDto implements Serializable {

    // 列名类型
    private String dataType;
    // 属性名称 下划线转驼峰
    private String attrName;
    // 列名
    private String columnName;
    // 数据库名
    private String tableName;
    // 属性类型
    private String attrType;
    // 主键
    private String priKey;
    // 是否允许空
    private String isNullable;
}

 下划线转驼峰工具类如下

public static String toFormatCol(String colName) {
    StringBuilder sb = new StringBuilder();
    String[] str = colName.toLowerCase().split("_");
    int i = 0;
    for (String s : str) {
        if (s.length() == 1) {
            s = s.toUpperCase();
        }
        i++;
        if (i == 1) {
            sb.append(s);
            continue;
        }
        if (s.length() > 0) {
            sb.append(s.substring(0, 1).toUpperCase());
            sb.append(s.substring(1));
        }
    }
    return sb.toString();
}

从数据库中查询出表的列名带下划线,字段为【columnName】,现在要将对应的字段转为驼峰并赋值到【attrName】

List<ColumnDto> columnDtoFromDB = new ArrayList<>();

columnDtoFromDB.stream().forEach( columnDto -> {
    // 下划线转驼峰
    columnDto.setAttrName(Common.toFormatCol(columnDto.getColumnName()));
});
  • Map集合

现有List<Map>集合,需要将Map中的key值全部由下划线转为驼峰

/**
 * 将List中map的key值命名方式格式化为驼峰
 *
 * @param
 * @return
 */
public static List<Map<String, Object>> formatHumpNameForList(List<Map<String, Object>> list) {
    List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
    for (Map<String, Object> o : list) {
        newList.add(formatHumpName(o));
    }
    return newList;
}

/**
 * 将Map中的key由下划线转换为驼峰
 *
 * @param map
 * @return
 */
public static Map<String, Object> formatHumpName(Map<String, Object> map) {
    Map<String, Object> newMap = new HashMap<String, Object>();
    Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        String key = entry.getKey();
        String newKey = toFormatCol(key);
        newMap.put(newKey, entry.getValue());
    }
    return newMap;
}

List内某字段求最大最小平均值

  • 实体如下
@Data
public class MonitorKw implements Comparable<MonitorKw> {
    /**
     * 采样时间
     */
    private String simpleTime;

    /**
     * 今日值
     */
    private Float todayValue;

    /**
     * 昨日值
     */
    private Float yesterdayValue;

    /**
     * 基线负荷
     */
    private Float baselineValue;
}
  •  求最大最小平均值
public static void calcList(List<MonitorKw> varList){

    // 最大值
    Folat max = varList.stream().max(Comparator.comparing(MonitorKw :: getBaselineValue)).get().getBaselineValue();
    // 最小值
    Float min = varList.stream().min(Comparator.comparing(MonitorKw :: getBaselineValue)).get().getBaselineValue();
    // 平均值
    Float avg = BigDecimal.valueOf(varList.stream().mapToDouble(MonitorKw :: getBaselineValue).average().getAsDouble()).floatValue()
}
  • float之前求差值的绝对值
BigDecimal b1 = new BigDecimal(Float.toString(float1));
BigDecimal b2 = new BigDecimal(Float.toString(float2));
float subtract = b1.subtract(b2).abs().floatValue();

List排序

  • 对象类型排序

将上述实体按【simpleTime】排序

list = list.stream().sorted(Comparator.comparing(MonitorKw::getSimpleTime)).collect(Collectors.toList());
  • 基础类型排序

 List中是基础类型,比如Integer, Long 等,排序方法很简单

//对数字进行排序
List<Integer> nums = Arrays.asList(3,1,5,2,9,8,4,10,6,7);
//reverseOrder倒序
nums.sort(Comparator.reverseOrder());
System.err.println("倒序:"+nums);
//naturalOrder自然排序即:正序
nums.sort(Comparator.naturalOrder());
System.err.println("正序:"+nums);

List中对象属性的合并(去重并求和)

        现有上述实体MonitorKw,将集合中【simpleTime】重复的实体去重,并将相同【simpleTime】的【baselineValue】值求和。

public static List<MonitorKw> merge(List<MonitorKw> list) {
    List<MonitorKw> result = list.stream()
            // 表示simpleTime为key, 接着如果有重复的,那么从MonitorKw对象o1与o2中筛选出一个,这里选择o1,
            // 并把simpleTime重复,需要将baselineValue与o1进行合并的o2, 赋值给o1,最后返回o1
            .collect(Collectors.toMap(MonitorKw::getSimpleTime, a -> a, (o1,o2)-> {
                o1.setBaselineValue(o1.getBaselineValue() + o2.getBaselineValue());
                return o1;
            })).values().stream().collect(Collectors.toList());
    return result;
}

Map<String, Object> 去除空的value值的key

 
    private static Map<String, Object> removeEmpty(Map<String, Object> map) {
        return map.entrySet().stream()
                .filter(entry -> entry.getValue() != null)
                .filter(entry -> !(entry.getValue() instanceof String) || !StringUtils.isEmpty(entry.getValue()))
                .filter(entry -> !(entry.getValue() instanceof List) || CollectionUtils.isNotEmpty((List) entry.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

List<List> 转换为 List 

List<List<String>> nestedList = new ArrayList<>();
nestedList.add(Arrays.asList("A", "B", "C"));
nestedList.add(Arrays.asList("D", "E"));
nestedList.add(Arrays.asList("F", "G", "H", "I"));
List<String> flatList = nestedList.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());

System.out.println(flatList);

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值