Last active
October 15, 2021 10:20
-
-
Save ValeryVerkhoturov/f7f80a62bde8b674f98ae51e51477626 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.company; | |
| import java.util.ArrayList; | |
| import java.util.concurrent.ThreadLocalRandom; | |
| import java.util.stream.Collectors; | |
| public class JavaSearchByClassType { | |
| public static void main(String[] args) { | |
| ArrayList<Object> objects = new ArrayList<>(); | |
| // запихиваем всякого | |
| for (int i = 0; i < 5; i++){ | |
| objects.add(Math.random()); | |
| objects.add((char)(ThreadLocalRandom.current().nextInt(25) + 65)); | |
| } | |
| System.out.println("Doubles: "); | |
| ArrayList<Double> doubles = findByClass(objects, Double.class); | |
| for (int i = 0; i < doubles.size(); i++) | |
| System.out.println(doubles.get(i).getClass() + " " + doubles.get(i)); | |
| System.out.println("Characters:"); | |
| ArrayList<Character> characters = findByClass(objects, Character.class); | |
| for (int i = 0; i < characters.size(); i++) | |
| System.out.println(characters.get(i).getClass() + " " + characters.get(i)); | |
| } | |
| private static <classType> ArrayList<classType> findByClass(ArrayList<?> list, Class<?> classType){ | |
| return (ArrayList<classType>) list.stream().filter(obj -> obj.getClass() == classType).map(classType::cast).collect(Collectors.toList()); | |
| } | |
| } | |
| //Doubles: | |
| //class java.lang.Double 0.7098515510570728 | |
| //class java.lang.Double 0.05707583089905499 | |
| //class java.lang.Double 0.7872549851678237 | |
| //class java.lang.Double 0.8752028316550686 | |
| //class java.lang.Double 0.408371159251227 | |
| // Characters: | |
| //class java.lang.Character I | |
| //class java.lang.Character E | |
| //class java.lang.Character H | |
| //class java.lang.Character R | |
| //class java.lang.Character P |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment