There is a MapMap, it transfers data to an array. In the array, the data is sorted, everything is fine. It is necessary to make such a method to take only 5 pieces from the array after sorting, which begin with the given letters.

For example, I entered abc and he returned to you a list of 5 values ​​that start with abc.

The main thing is that exactly 5 values ​​and the order of the files should not be lost (they are already sorted by date \ alphabet)

public static void main(String[] args) { TreeMap<File, Class> classesByFiles = find("com.company", ""); // ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ» ΠΌΠ°ΠΏΡƒ List<File> files = new ArrayList<>(classesByFiles.keySet()); //ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ» список Ρ„Π°ΠΉΠ»ΠΎΠ² ΠΈΠ· ΠΌΠ°ΠΏΡ‹ Collections.sort(files, MODIFIED_DATE_FILE_COMPARATOR);// посортировал for (File file : files) // ΠΈΠ΄Π΅ΠΌ ΠΏΠΎ массиву { System.out.println(file);// Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ Π΅Π³ΠΎ Π½Π° ΠΏΠ΅Ρ‡Π°Ρ‚ΡŒ для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ } 
  • what is the question? And why create an array in the TreeMap keys are also sorted. - pavel
  • @pavel In the 'Treemap' they are sorted alphabetically, and we need first of all by the date of the last change. The essence of the question is to get from the already sorted array only 5 values ​​starting with the entered characters. - Dmitrii

1 answer 1

Something like that

 List<File> abc = files.stream().filter(f -> f.getName().startsWith("abc")) .limit(5).collect(Collectors.toList()); 

Or so

 { public static void main(String[] args) throws InvalidArgumentException { List<File> files = new ArrayList<>(); files.add(new File("C:/test/")); files.add(new File("abc1")); files.add(new File("abc2")); files.add(new File("abc3")); files.add(new File("weabc4")); files.add(new File("abc5")); files.add(new File("sdabc5")); files.add(new File("abc4")); Collections.sort(files); String startName = "abc"; List<File> files1 = getFiles(files, startName); files1.forEach(f -> System.out.println(f.getName())); } public static List<File> getFiles(List<File> files, String startName){ List<File> listFiles = new ArrayList<>(); for (File file : files) { if(file.getName().startsWith(startName)) listFiles.add(file); } if(listFiles.size() > 5) return listFiles.subList(0, 5); return listFiles; } } 
  • Red emphasizes stream, getName and Collectors - Dmitrii
  • these are the settings of your IDE, ALT + Enter and show you the mole to add to the exception and import Collectors - Senior Pomidor
  • There is no such import. This is not the eighth Java case? At 7 everything else is written. - Dmitrii
  • eh. 8th tomorrow I will write another code - Senior Pomidor
  • @Dmitrii sorry, I’m not able to add code properly ((( - Senior Pomidor