list.stream().map().collect(Collectors.toList())

本文介绍 Java Stream API 的核心操作,如 map 和 filter 方法,并演示如何将 List 转换为 Map,以及如何进行数据过滤和转换。同时,还展示了如何实现数据去重和集合间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java api 特性
stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成
map():用于映射每个元素到对应的结果。
filter():filter 方法用于通过设置的条件过滤出元素。
Collectors.toList() 用来结束Stream流
例如:
//userList User实体类对象集合
//User 实体类
//getId 实体类属性的get方法 
List<int> ids= userList.stream().map(User::getId).collect(Collectors.toList())
//或者  把数据放到map根据user.getId(条件) 循环 在转换成list
List<int> ids= userList.stream().map(user->user.getId()).collect(Collectors.toList());

//过滤list集合中属性type为1的值并赋值给permissions集合 在返回list集合 .collect(Collectors.toList()) 转换成list集合
List<Permission> permissions = list.stream().filter(l -> l.getType().equals(1))
                .collect(Collectors.toList());
 

list转map

Map<String,Entity> statMap = statList.stream().collect(Collectors.toMap(Entity::getId, Entity -> Entity));
        
List<String> collect = roleResultList.stream().map(AcAppRole::getName).collect(Collectors.toList());
Map<Integer, String> map = new HashMap<>();
map.put(10, "apple");
map.put(20, "orange");
map.put(30, "banana");
map.put(40, "watermelon");
map.put(50, "dragonfruit");
System.out.println("\n1. Export Map Key to List...");
List<Integer> result = map.keySet().stream().collect(Collectors.toList());
result.forEach(System.out::println);
System.out.println("\n2. Export Map Value to List...");
List<String> result2 = map.values().stream().collect(Collectors.toList());
result2.forEach(System.out::println);
System.out.println("\n3. Export Map Value to List..., say no to banana");
List<String> result3 = map.keySet().stream().filter(x -> !"banana".equalsIgnoreCase(x)).collect(Collectors.toList());
result3.forEach(System.out::println);
 
List<String> resultValues = map.entrySet().stream().sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
                .peek(e -> resultSortedKey.add(e.getKey()))
                .map(x -> x.getValue())
                .filter(x -> !"banana".equalsIgnoreCase(x))
                .collect(Collectors.toList());
 
    public static void main(String args[]) {
        SqlServerReader tester = new SqlServerReader();
        tester.testCaseFormat();
    }
 
    private void testCaseFormat() {
        System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, "test-data"));
        System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "test_data"));
        System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "test_data"));
 
        System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "testdata"));
        System.out.println();
        System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "testData"));
    }
 

list转逗号分隔的字符串CollectionUtil.join

List<SysRole> roleList = sysRoleService.list(roleWrapper);
List<String> roleIdList = roleList.stream().map(SysRole::getId).collect(Collectors.toList());
List<String> roleNames = roleList.stream().map(SysRole::getRoleName).collect(Collectors.toList());
sysUser.setUserRoleNames(CollectionUtil.join(roleNames, ","));

字符串转list

List<Long> shipIdList = Arrays.stream(shipIds.split(",")).map(Long::parseLong).collect(Collectors.toList());

list根据某个对象属性去重

// 根据name去重
List<Person> unique = persons.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);

// 根据name,sex两个属性去重
List<Person> unique = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);

List<Person> filterList = persons.stream().filter(p -> p.getSex().equals(1)).collect(Collectors.toList());

`list.stream().collect(Collectors.toMap())` 是 Java 8 中的 Stream API 的一个用法,它可以将一个 List 转换成一个 Map。其中,List 中每个元素都被映射成一个 Map 的 key-value 对。 具体来说,`list.stream()` 将 List 转换成一个 Stream,然后通过 `collect(Collectors.toMap())` 方法将 Stream 中的元素收集到一个新的 Map 中。 `Collectors.toMap()` 方法有多个重载形式,最常用的一种形式接受两个 Function 对象,分别用于指定 key 和 value 的提取方式。例如: ```java List<Person> people = Arrays.asList( new Person("Alice", 20), new Person("Bob", 30), new Person("Charlie", 40) ); Map<String, Integer> ageByName = people.stream() .collect(Collectors.toMap( person -> person.getName(), // key 提取函数 person -> person.getAge() // value 提取函数 )); ``` 上述代码中,`people` 是一个包含三个 Person 对象的 List。我们通过 `people.stream()` 将其转换成一个 Stream,然后通过 `collect(Collectors.toMap())` 方法将其中每个元素映射成一个 key-value 对,并以此构造一个新的 Map。其中,key 由 `person.getName()` 提取,value 由 `person.getAge()` 提取。 最终得到的 `ageByName` Map 的结构如下: ``` { "Alice": 20, "Bob": 30, "Charlie": 40 } ``` 注意,如果 List 中存在重复的 key,那么会抛出一个 `IllegalStateException` 异常。如果你需要处理这种情况,可以使用 `toMap()` 方法的另一种重载形式,该方法接受一个合并函数,用于指定当出现重复 key 时如何处理 value。例如: ```java List<Person> people = Arrays.asList( new Person("Alice", 20), new Person("Bob", 30), new Person("Charlie", 40), new Person("Alice", 50) ); Map<String, Integer> ageByName = people.stream() .collect(Collectors.toMap( person -> person.getName(), person -> person.getAge(), (age1, age2) -> age1 + age2 // 合并函数,将重复 key 的 value 相加 )); ``` 上述代码中,`people` 中有两个名字为 "Alice" 的 Person 对象,因此在转换成 Map 时会出现重复的 key。我们通过 `(age1, age2) -> age1 + age2` 指定了一个合并函数,用于将重复 key 的 value 相加。最终得到的 `ageByName` Map 的结构如下: ``` { "Alice": 70, "Bob": 30, "Charlie": 40 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值