Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an ArrayList from a Intstream

so I want to put Person into an array list but I need to use streams I have csv file thath give me infomartions id;name;sex and a method to turn these into a Person object using there id,

private Person readCSVLines(int id);

but I want to create a method giving me an arrays list of all of them I know there is 807 id and there will be no one more

I tried this using toMap but it worked giving me a map but I only want an ArrayList:

public ArrayList<Person> getAllPerson() {
        try (IntStream stream = IntStream.range(1, personmax)) { // personmax is 807 here
            return stream.boxed().collect(
                    Collectors.toMap(
                            i -> i,
                            this::readCSVLines,
                            (i1, i2) -> {
                                throw new IllegalStateException();
                            },
                            ArrayList::new
                    )
            );
        }
    }
like image 263
lolozen Avatar asked Dec 08 '25 01:12

lolozen


1 Answers

In your case you just have to iterate over all of the rows using IntStream.range(from, to) and convert each row number into the object read from csv with the help of .mapToObj(). It's redundant to use boxed() function in this case. Finally, what you need is

    public List<Person> getAllPerson() {
       return IntStream
            .range(1, personmax) // personmax is 807 here
            .mapToObj(this::readCSVLines)
            .collect(Collectors.toList());
       }
    }

Also, note that your methods should have interface as return type (List) instead of concrete implementation (ArrayList)

like image 178
Stepan Tsybulski Avatar answered Dec 10 '25 13:12

Stepan Tsybulski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!