You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java 8实现字符串列表转对象列表及文件JSON流转User列表

Hey folks, let's walk through the Java 8 solutions for your two scenarios clearly and concisely:

1. Convert List to List

Since String is a direct subclass of Object, this conversion is super straightforward. Using Java 8 streams, we can achieve it in a clean, declarative way:

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

public class StringToObjectListExample {
    public static void main(String[] args) {
        List<String> stringList = List.of("apple", "banana", "cherry");
        
        // Convert List<String> to List<Object>
        List<Object> objectList = stringList.stream()
                .map(s -> (Object) s) // Explicit cast (optional but clarifies intent)
                .collect(Collectors.toList());
        
        // Verify the result
        objectList.forEach(System.out::println);
    }
}

Note: The explicit cast (Object)s isn't strictly necessary (since String is inherently an Object), but including it makes the conversion intent clearer for anyone reading the code.

2. Read File Stream and Convert JSON Lines to List

For this scenario, we'll use Jackson's ObjectMapper (a widely used JSON processing library) to parse each line of JSON into a User object. First, ensure you have the Jackson dependency in your project (for Maven, add this to your pom.xml):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest stable version available -->
</dependency>

Here's the Java 8 implementation, using streams and try-with-resources to safely handle file I/O:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class JsonFileToUserListExample {
    // Reusable ObjectMapper instance (more efficient than creating new ones per line)
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) {
        String filePath = "path/to/your/json/file.txt";
        
        try {
            // Read file lines, parse each JSON to User, collect into a list
            List<User> userList = Files.lines(Paths.get(filePath))
                    .filter(line -> !line.isBlank()) // Skip empty/whitespace-only lines
                    .map(jsonLine -> {
                        try {
                            return objectMapper.readValue(jsonLine, User.class);
                        } catch (IOException e) {
                            // Handle parsing errors (log and skip invalid lines)
                            System.err.println("Failed to parse JSON line: " + jsonLine);
                            e.printStackTrace();
                            return null;
                        }
                    })
                    .filter(user -> user != null) // Remove entries from failed parsing
                    .collect(Collectors.toList());
            
            // Use the resulting user list
            userList.forEach(user -> 
                System.out.printf("UID: %s, Is Hot: %b%n", user.getUid(), user.getIsHot())
            );
        } catch (IOException e) {
            System.err.println("Failed to read file: " + filePath);
            e.printStackTrace();
        }
    }
}

// Your provided User class
class User {
    private String uid;
    private long timestamp;
    private boolean isHot;
    
    public String getUid() { return uid; }
    public void setUid(String uid) { this.uid = uid; }
    public long getTimestamp() { return timestamp; }
    public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
    public boolean getIsHot() { return isHot; }
    public void setIsHot(boolean isHot) { this.isHot = isHot; }
}

Key Notes:

  • Files.lines() returns a stream that automatically closes the file resource when used with try-with-resources, preventing resource leaks.
  • We filter out empty lines upfront to avoid unnecessary parsing attempts.
  • Parsing exceptions are handled inline: invalid lines are logged, and we filter out any null entries from failed conversions to keep the list clean.

内容的提问来源于stack exchange,提问作者xiaofeng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:56:36