@Test
public void testList(){
List<Map<String,String>> list = new ArrayList<>();
Map<String,String> map = new HashMap<>();
map.put("a", "aa");
map.put("status", "1");
map.put("b", "bb");
map.put("sign1", "5");
map.put("sign2", "4");
list.add(map);
Map<String,String> map1 = new HashMap<>();
map1.put("c", "cc");
map1.put("statu", "0");
map1.put("d", "dd");
map1.put("sign1", "2");
map1.put("sign2", "9");
list.add(map1);
Map<String,String> map2 = new HashMap<>();
map2.put("c1", "cc1");
map2.put("statu1", "0");
map2.put("d1", "dd1");
map2.put("sign1", "4");
map2.put("sign2", "2");
list.add(map2);
Map<String,String> map3 = new HashMap<>();
map3.put("c1", "cc1");
map3.put("statu1", "0");
map3.put("d1", "dd1");
map3.put("sign1", "3");
map3.put("sign2", "1");
list.add(map3);
int[] i = {
0};
int flag = 9;
list.forEach(item ->{
//item 为list 的第一个的map --> {
a=aa, b=bb, status=1}
//item 为list中的元素;
i[0] += 1;
// System.out.println(i[0]);
// System.out.println(flag+"--------------------");
//flag +=1; ==>报错,放到list或arr中可以用于计算;
System.out.println(item);
// System.out.println("第"+i+"次循环");
String status = item.get("status");
String statu = item.get("statu");
// System.out.println(status);
// System.out.println(statu);
});
System.out.println("==========================");
//筛选符合条件的list中的值,转为list,在放到list1中;
List<Map<String,String>> list1 = list.stream().filter(a -> "1".equals(a.get("status"))||"0".equals(a.get("statu"))).collect(Collectors.toList());
//Stream<Map<String,String>> aa = list.stream().filter(a -> "1".equals(a.get("status")));
list1.forEach(item ->{
System.out.println(item);
});
System.out.println("==========================");
//根据某个字段,进行排序。list中map里都包含sign2这个参数,用这个参数进行排序
//如果sign2这个参数为null或 "",或这个参数不存在,可为其赋予一个值,此处为"0"
list.sort((a,b) ->
a.getOrDefault("sign2", "0").compareTo(b.getOrDefault("sign2", "0"))
);
list.forEach(item ->{
System.out.println(item);
});
System.out.println("****************************************");
// .skip(x):去除集合中前x个元素
// .limit(y):截取当前集合中y个元素
list = list.stream().skip(2).limit(1).collect(Collectors.toList());
list.forEach(item ->{
System.out.println(item);
});
}
运行结果
{
sign2=4, a=aa, sign1=5, b=bb, status=1}
{
sign2=9, sign1=2, c=cc, d=dd, statu=0}
{
sign2=2, sign1=4, statu1=0, d1=dd1, c1=cc1}
{
sign2=1, sign1=3, statu1=0, d1=dd1, c1=cc1}
==========================
{
sign2=4, a=aa, sign1=5, b=bb, status=1}
{
sign2=9, sign1=2, c=cc, d=dd, statu=0}
==========================
{
sign2=1, sign1=3, statu1=0, d1=dd1, c1=cc1}
{
sign2=2, sign1=4, statu1=0, d1=dd1, c1=cc1}
{
sign2=4, a=aa, sign1=5, b=bb, status=1}
{
sign2=9, sign1=2, c=cc, d=dd, statu=0}
****************************************
{
sign2=4, a=aa, sign1=5, b=bb, status=1}