By using streams and lambda expressions, you can reduce the coding of list sorting.
Main.java
package sample;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
//List setting (method without add method)
List<String> sampleList = List.of("Ishikari","Sorachi","Shiribeshi","Iburi","Hidaka","Hiyama","Oshima","Rumoi","Kamikawa","Soya","Tokachi","Kushiro","Okhotsk","Nemuro");
//Check the created list samples
System.out.println(sampleList);
System.out.println("");
//Sort the created list samples using streams and lambda expressions
// A → Z
List<String> sortedSampleList1 = sampleList.stream().sorted((a,b) -> (a.compareTo(b))).collect(Collectors.toList());
System.out.println("A → Z");
System.out.println(sortedSampleList1);
System.out.println("");
// Z → A
System.out.println("Z → A");
List<String> sortedSampleList2 = sampleList.stream().sorted((a,b) -> (b.compareTo(a))).collect(Collectors.toList());
System.out.println(sortedSampleList2);
}
}
[Ishikari, Sorachi, Shiribeshi, Iburi, Hidaka, Hiyama, Oshima, Rumoi, Kamikawa, Soya, Tokachi, Kushiro, Okhotsk, Nemuro]
A → Z
[Hidaka, Hiyama, Iburi, Ishikari, Kamikawa, Kushiro, Nemuro, Okhotsk, Oshima, Rumoi, Shiribeshi, Sorachi, Soya, Tokachi]
Z → A
[Tokachi, Soya, Sorachi, Shiribeshi, Rumoi, Oshima, Okhotsk, Nemuro, Kushiro, Kamikawa, Ishikari, Iburi, Hiyama, Hidaka]
In programming (Java) of the Fundamental Information Technology Engineer Examination, code using stream lambda expressions is sometimes given as a subject.
Recommended Posts