Sitemap
Vijay

Vijay

Writing Content | Reading Books | krvijay155@gmail.com | iamvijay.gumroad.com/

Java One Liner Hacks

2 min readJan 10, 2023

--

In this post, I will share with you multiple Java one-liner code snippets (okay, they may be a bit longer) that will help you in many commonly occurring repetitive tasks.

Sum a range of numbers

// this will sum all the numbers from 1 to 1000, excluding 1000
int totalSum = IntStream.range(1, 1000).sum()

Check if a String/Document contains at least one of the keywords

//converts 'keywords' to Java stream and anyMatch method tests 
//against the Predicate or the condition that we have provided

List<String> keywords= Arrays.asList( "Java", "Love", "World", "Fire");
String sentence = "Java is magical. I love it so much";
System.out.println(keywords.stream().anyMatch(sentence::contains));

Copy a file from one path to another

//the first path is the source, second is the destination
Files.copy(Paths.get("E:\\interview.txt"),Paths.get("D:\\newFile.txt"));

Make an unmodifiable collection

//The collection stored in 'listOfNames' cannot be changed
final Collection listOfNames =
Collections.unmodifiableCollection(Arrays.asList("Jack","John","Steve"));

Faster Multiplication and Division

//Shifts the bit position to left and right respectively by 1 place
num = num << 1; // Multiply n with 2
num = num >> 1; // Divide n by 2

Get Vijay’s stories in your inbox

Join Medium for free to get updates from this writer.

Input a character using the ‘Scanner’ class

//reading a line and extracting the first character
char c = scanner.next().charAt(0);

Reverse an Array

//converts the numbers to stream and reverses them
//you can also collect it into a list instead of printing
List<Integer> nums = Arrays.asList(5,6,7,8);
nums.stream()
.sorted(Collections.reverseOrder())
.forEach(System.out::println);

Read a text file into Java

//this will read whole file in a String variable
String textCorpus = new String(Files.readAllBytes(Paths.get("E:\\interview.txt")));
//this will read each line into a List item
List<String> fileLines= Files.readAllLines(Paths.get("E:\\interview.txt"));

Convert a String to a character Array

  String str = "BeautifulWorld";
char[] charArrayStr = str.toCharArray();

Convert a “Date” string to a “Date Object”

//Tue Jan 10 00:00:00 IST 2023
Date myDate = new SimpleDateFormat("dd-MM-yyyy").parse("10-01-2023");

Remove duplicates from a list

List<Integer> listOfNumbers = Arrays.asList(4,4,2,1,5,6,7,5,6,1);
listOfNumbers.stream().distinct().forEach(System.out::println);

Convert a List to Map

Map<String, Item> result = items.stream()
.collect(Collectors.toMap(item -> item.getName(), item -> item));

Dear reader, Medium Partner Program is not available in India. If you liked my content, consider contributing and helping keep this page alive.
PayPal:
http://paypal.me/iamvijay64
UPI/Cards:
https://www.instamojo.com/@iamvijay

--

--